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
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.
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.
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.
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.
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">
you need object notation
<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" >
ref: NgClass
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