Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions in ngClass - Angular 4

Tags:

angular

How to use multiple conditions for ngClass? Example:

<section [ngClass]="[menu1 ? 'class1' : '' || menu2 ? 'class1' : '' || (something && (menu1 || menu2)) ? 'class2' : '']"> 

something like this. I got same class for 2 menus, and I need class when one of those menus is true and 'something' is true. Hope I explained well enough

like image 318
Nemanja G Avatar asked Jun 29 '17 09:06

Nemanja G


People also ask

How do you add conditions to ngClass?

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.

Can we use two ngClass in angular?

Angular's NgClass Directive So far we've looked at adding just single classes, which is something the NgClass directive can also help us with as it supports multiple classes. Using multiple classes is the real reason to use the NgClass directive. You can think of NgClass as being able to specify multiple [class.

Can we use NGIF and ngClass together?

javascript - ng-if and ng-class-even/odd doesn't work well together and won't get expected outout - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Can I use both class and ngClass?

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.


2 Answers

You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a || instead of a ,.

Try this:

<section [ngClass]="[menu1 ? 'class1' : '',  menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']"> 

This other option should also work:

<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">     
like image 85
Matthias247 Avatar answered Sep 20 '22 18:09

Matthias247


you need object notation

<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" >  

ref: NgClass

like image 23
dee zg Avatar answered Sep 18 '22 18:09

dee zg