Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if something is in array from ng-class

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 ...
like image 871
Jhony Blaze Avatar asked Apr 22 '16 20:04

Jhony Blaze


People also ask

Can you use ngClass and class?

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.

How do you use NG conditional class?

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.

Is ngClass a directive?

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.

Can we call method in ngClass in angular?

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.


1 Answers

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}"
like image 125
adeneo Avatar answered Oct 29 '22 07:10

adeneo