If input is null enter key should not call the function "generateCityDetailArray()" means it should be disabled, otherwise it should call the function "generateCityDetailArray()". How to achieve this?
<div class="form-group">
<input type = "text" class="col2" formControlName="pinCode"
[(ngModel)]="pinCode" required (keyup.enter)="generatecityDetailArray()" maxlength="6" />
<div *ngIf="f.pinCode.invalid && f.pinCode.touched"><strong class="text-danger" *ngIf="f.pinCode.errors?.required">Please enter the value!</strong></div>
</div>
Now, If I click enter in textbox, it is calling "generateCityDetailArray()" even when input is null. What required is if input is null and If enter is clicked then it should give a message like "Plz Enter pincode", "generateCityDetailArray()" should not be called when input is null.
why not just start method generatecityDetailArray() by
if (!this.pinCode) {
return;
}
if you have form control on input you can launch method only when input have no error
(keyup.enter)="pinCode.errors ? '' : generatecityDetailArray()"
If you want to display message to say you have to enter pincode you can use follwing syntaxe
<div *ngIf="pinCode.errors?.['required']">
Please Enter pincode.
</div>
in your class you have to define getter and setter of the form control
get pinCode() { return this.cityDetailForm.get('pinCode'); }
here the doc about validators
https://angular.io/guide/form-validation
The suggestion of starting the generatecityDetailArray() method with a check if you have a value of pinCode is a great option.
If you want to have your check performed in the template, you can also do the following:
(keyup.enter)="cityDetailForm.get('pinCode').invalid ? $event.preventDefault() : generatecityDetailArray()"
This is if you have only one validator setup for the pinCode formControl.
If you have multiple make the check cityDetailForm.get('pinCode').errors?['required'].
Also this is assuming that cityDetailForm is your formGroup. I previously thought it was simply f, because of the ngIf check on your div.
It would be best to have a getter in the component for this case, so it would be something like:
get isCityDetailInValid(): boolean {
return this.cityDetailForm.get('pinCode').errors?['required'];
// or this.cityDetailForm.get('pinCode').invalid;
}
Then your template would simply be:
(keyup.enter)="isCityDetailInValid ? $event.preventDefault() : generatecityDetailArray()"
Have been looking for this answer in SO, but perhaps I'm not frasing it correctly or there is actually no answer yet for this.
I am using an input component that uses a key to render it valid (green border) or invalid (red border) and I would like to add it dynamically:
<Input type="select" valid /> //This input has green border
<Input type="select" invalid /> //This input has red border
Since they key valid/invalid has no value like true or false, I'm not sure how to change it dynamically through a function since as far as I'm aware, I can change values dynamically with a JSX expression, but not add a key itself.
Can you please suggest a way to add 'valid' or 'invalid' tag dynamically without value?
"Without value" is actually not accurate. What you see there is syntactic sugar for valid={true} and invalid={true}.
So, the same can be accomplished by:
const valid = // whatever logic here to determine if it's valid.
<Input type="select" valid={valid} invalid={!valid} /> // Either return or assign to something.
Alternatively:
let inputProps = {type: 'select'};
if (/* whatever logic here to determine if it's valid*/) {
inputProps.valid = true;
}
else {
inputProps.invalid = true;
}
<Input {...inputProps} />; // Either return or assign to something.
But the latter is a lot more verbose.
Not sure if this will work but give it a try.
JSX reads properties without values/= as boolean/true.
Set null values:
<Input type="select" invalid={null} />
You can then conditionally show valid or invalid input elements
I am not quite sure how to bind a variable from my component class to a property value in my form object. The form needs to display this value and add it to the ngModel so that it can become part of the object instance.
I am struggling with the syntax and keep getting the errorNo value accessor for form control with name: 'per_print'
Error: No value accessor for form control with name: I think I need to use the [(ngModel)]="myObject.property" syntax, but I am not getting this from an input into the form, but from a binded variable on the class.
<div class="form-group">
<label class="label-text" >Per Print</label>
<div class="input-group" style="width:150px;">
<h4 [(ngModel)]="job_entry.per_print" name="per_print"
value='pricePerPrint' class="form-control"
>
{{pricePerPrint | currency:'GBP':true:'1.2-2'}}
</h4>
</div>
</div>
job_entry is my object which properties I am setting through the form. pricePerPrint is a variable on the class. I want to set this variable to one of the form instance properties. How to do this? I thought I could do it through value, as in the value of the <h4> tag, but this error persists.
You could use [hidden] input field with the value you want, so that this value will be added to your form. This means though, that you need to use pricePerPrint as the ngModel. But ngModel for your job_entry is possibly not needed. You could build the form as such, so that the object you get from the form can be assigned directly to job_entry:
onSubmit(obj) {
this.job_entry = obj;
}
Also check the Demo for that.
So your code would look like this:
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm.value)">
<input [hidden]="isHidden" name="per_print"
[(ngModel)]="pricePerPrint" [value]="pricePerPrint"/>
<h4>Price: {{pricePerPrint}}</h4>
<button type="submit">Submit</button>
</form>
where isHidden is set to true.
Other option I see, if you want to use [(ngModel)]="job_entry.per_print, you need to assign whatever value you have in pricePerPrint to job_entry.per_print.
Trying to do something I thought is pretty simple but it's turning out to be pretty annoying. I'm just trying to have a function that runs when you click on a checkbox using the ng-checked directive.
This is the HTML:
<div class="form-group">
<label class="col-sm-2 control-label">Make Payment Optional</label>
<div class="col-sm-4 center-checkbox">
<input type="checkbox"
class="center-checkbox"
ng-model="formData.optionalPayment"
ng-checked="optionalPaymentCheckbox();"
validate-servererror="featured"/>
</div>
</div>
And this is the Angular:
if($scope.formData.optionalPayment === undefined) {
$scope.formData.optionalPayment = TournamentConst.PAYMENT.OPTIONAL;
}
(This check is just for when I load the page for the first time.)
$scope.optionalPaymentCheckbox = function () {
if($scope.formData.optionalPayment === TournamentConst.PAYMENT.OPTIONAL) {
$scope.formData.optionalPayment = TournamentConst.PAYMENT.MANDATORY;
} else {
$scope.formData.optionalPayment = TournamentConst.PAYMENT.OPTIONAL;
}
};
When I load the page, this ng-checked function runs infinitely. Is there something about the ng-checked directive I don't know, or some minor detail or forgot? Thanks in advance.
You are misunderstanding the intention of ng-checked. What you think it does is "execute this expression when the checkbox is checked" - an event handler directive.
What it actually does is set the checked property based on the expression. This means it sets up a watch on the expression and evaluates it every digest. If the value changes, it sets or unsets the checked property accordingly.
In fact, the documentation for ng-checked says this:
Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.
As #JB Nizet correctly pointed out, you can achieve the desired effect in your particular case by using ng-true-value and ng-false-value and removing ng-checked altogether.
So your HTML becomes:
<div class="form-group">
<label class="col-sm-2 control-label">Make Payment Optional</label>
<div class="col-sm-4 center-checkbox">
<input type="checkbox"
class="center-checkbox"
ng-model="formData.optionalPayment"
ng-true-value="TournamentConst.PAYMENT.MANDATORY"
ng-false-value="TournamentConst.PAYMENT.OPTIONAL"
validate-servererror="featured"/>
</div>
</div>
Then, in your controller, populate your TournamentConst object in the scope, so the template can see it:
$scope.TournamentConst = TournamentConst;
(or you can just populate the bits you need)
Finally, get rid of the whole $scope.optionalPaymentCheckbox function. You will still need the code to set the default value, though.
One last thing: It is confusing that the property is called optionalPayment, when it is really more like paymentType, but that is not related to the current problem.
Is there any way to make an expression for something like ng-class to be a conditional?
For example, I have tried the following:
<span ng-class="{test: 'obj.value1 == \'someothervalue\''}">test</span>
The issue with this code is that no matter what obj.value1 is, the class test is always applied to the element. Doing this:
<span ng-class="{test: obj.value2}">test</span>
As long as obj.value2 does not equal a truthy value, the class in not applied. Now I can work around the issue in the first example by doing this:
<span ng-class="{test: checkValue1()}">test</span>
Where the checkValue1 function looks like this:
$scope.checkValue1 = function() {
return $scope.obj.value === 'somevalue';
}
I am just wondering if this is how ng-class is supposed to work. I am also building a custom directive where I would like to do something similar to this. However, I can't find a way to watch an expression (and maybe that is impossible and the reason why it works like this).
Here is a plnkr to show what I mean.
Your first attempt was almost right, It should work without the quotes.
{test: obj.value1 == 'someothervalue'}
Here is a plnkr.
The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here.
If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.
Just to complement: You can also use logical operators to form logical expressions like
ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"
Using ng-class inside ng-repeat
<table>
<tbody>
<tr ng-repeat="task in todos"
ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',
'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">
<td>{{$index + 1}}</td>
<td>{{task.name}}</td>
<td>{{task.date|date:'yyyy-MM-dd'}}</td>
<td>{{task.status}}</td>
</tr>
</tbody>
</table>
For each status in task.status a different class is used for the row.
Angular JS provide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.
Type 1
<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>
In this code class will be apply according to value of status value
if status value is 0 then apply class one
if status value is 1 then apply class two
if status value is 2 then apply class three
Type 2
<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>
In which class will be apply by value of status
if status value is 1 or true then it will add class test_yes
if status value is 0 or false then it will add class test_no
I see great examples above but they all start with curly brackets (json map). Another option is to return a result based on computation. The result can also be a list of css class names (not just map). Example:
ng-class="(status=='active') ? 'enabled' : 'disabled'"
or
ng-class="(status=='active') ? ['enabled'] : ['disabled', 'alik']"
Explanation: If the status is active, the class enabled will be used. Otherwise, the class disabled will be used.
The list [] is used for using multiple classes (not just one).
There is a simple method which you could use with html class attribute and shorthand if/else. No need to make it so complex. Just use following method.
<div class="{{expression == true ? 'class_if_expression_true' : 'class_if_expression_false' }}">Your Content</div>
I am going to show you two methods by which you can dynamically apply ng-class
Step-1
By using ternary operator
<div ng-class="condition?'class1':'class2'"></div>
Output
If your condition is true then class1 will be applied to your element else class2 will be applied.
Disadvantage
When you will try to change the conditional value at run time the class somehow will not changed. So I will suggest you to go for step2 if you have requirement like dynamic class change.
Step-2
<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>
Output
if your condition matches with value1 then class1 will be applied to your element, if matches with value2 then class2 will be applied and so on. And dynamic class change will work fine with it.
Hope this will help you.
Angular syntax is to use the : operator to perform the equivalent of an if modifier
<div ng-class="{ 'clearfix' : (row % 2) == 0 }">
Add clearfix class to even rows. Nonetheless, expression could be anything we can have in normal if condition and it should evaluate to either true or false.
Using function with ng-class is a good option when someone has to run complex logic to decide the appropriate CSS class.
http://jsfiddle.net/ms403Ly8/2/
HTML:
<div ng-app>
<div ng-controller="testCtrl">
<div ng-class="getCSSClass()">Testing ng-class using function</div>
</div>
</div>
CSS:
.testclass { Background: lightBlue}
JavaScript:
function testCtrl($scope) {
$scope.getCSSClass = function() {
return "testclass ";
}
}
For Angular 2, use this
<div [ngClass]="{'active': dashboardComponent.selected_menu == 'mapview'}">Content</div>
use this
<div ng-class="{states}[condition]"></div>
for example if the condition is [2 == 2], states are {true: '...', false: '...'}
<div ng-class="{true: 'ClassA', false: 'ClassB'}[condition]"></div>
ng-class is a Directive of core AngularJs. In which you can use "String Syntax", "Array Syntax", "Evaluated Expression", " Ternary Operator" and many more options described below:
ngClass Using String Syntax
This is the simplest way to use ngClass. You can just add an Angular variable to
ng-class and that is the class that will be used for that element.
<!-- whatever is typed into this input will be used as the class for the div below -->
<input type="text" ng-model="textType">
<!-- the class will be whatever is typed into the input box above -->
<div ng-class="textType">Look! I'm Words!
Demo Example of ngClass Using String Syntax
ngClass Using Array Syntax
This is similar to the string syntax method except you are able to apply multiple classes.
<!-- both input boxes below will be classes for the div -->
<input type="text" ng-model="styleOne">
<input type="text" ng-model="styleTwo">
<!-- this div will take on both classes from above -->
<div ng-class="[styleOne, styleTwo]">Look! I'm Words!
ngClass Using Evaluated Expression
A more advanced method of using ngClass (and one that you will probably use the most) is to evaluate an expression. The way this works is that if a variable or expression evaluates to true, you can apply a certain class. If not, then the class won't be applied.
<!-- input box to toggle a variable to true or false -->
<input type="checkbox" ng-model="awesome"> Are You Awesome?
<input type="checkbox" ng-model="giant"> Are You a Giant?
<!-- add the class 'text-success' if the variable 'awesome' is true -->
<div ng-class="{ 'text-success': awesome, 'text-large': giant }">
Example of ngClass Using Evaluated Expression
ngClass Using Value
This is similar to the evaluated expression method except you just able to compares multiple values with the only variable.
<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>
ngClass Using the Ternary Operator
The ternary operator allows us to use shorthand to specify two different classes, one if an expression is true and one for false. Here is the basic syntax for the ternary operator:
ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">
Evaluating First, Last or Specific Number
If you are using the ngRepeat directive and you want to apply classes to the first, last, or a specific number in the list, you can use special properties of ngRepeat. These include $first, $last, $even, $odd, and a few others. Here's an example of how to use these.
<!-- add a class to the first item -->
<ul>
<li ng-class="{ 'text-success': $first }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
<!-- add a class to the last item -->
<ul>
<li ng-class="{ 'text-danger': $last }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
<!-- add a class to the even items and a different class to the odd items -->
<ul>
<li ng-class="{ 'text-info': $even, 'text-danger': $odd }" ng-repeat="item in items">{{ item.name }}</li>
</ul>