I want to do something like:
var list = [1,2,3,4,5]
if(2 in list){
return true
}
from a ng-class
, so I tried:
ng-class="this.id in list ? 'class-1' : 'class-2' ">
But doesn't worked, throws an error
Syntax Error: Token 'in' is an unexpected token at ...
You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.
To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.
The ng-class directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array.
You can use a method and a variable to construct the classes-string for the ngClass. In Template then you can use a method and a variable to construct the classes-string for the ngClass.
For arrays you'd use indexOf
, not in
, which is for objects
if ( list.indexOf(this.id) !== -1 ) { ... }
so
ng-class="{'class-1' : list.indexOf(this.id) !== -1, 'class-2' : list.indexOf(this.id) === -1}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With