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
This question is related to
angular
<section [ngClass]="{'class1': expression1, 'class2': expression2,
'class3': expression3}">
Don't forget to add single quotes around class names.
I hope this is one of the basic conditional classes
Solution: 1
<section [ngClass]="(condition)? 'class1 class2 ... classN' : 'another class1 ... classN' ">
Solution 2
<section [ngClass]="(condition)? 'class1 class2 ... classN' : '(condition)? 'class1 class2 ... classN':'another class' ">
Solution 3
<section [ngClass]="'myclass': condition, 'className2': condition2">
you need object notation
<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" >
ref: NgClass
<a [ngClass]="{'class1':array.status === 'active','class2':array.status === 'idle','class3':array.status === 'inactive',}">
I had this similar issue. I wanted to set a class after looking at multiple expressions. ngClass can evaluate a method inside the component code and tell you what to do.
So inside an *ngFor:
<div [ngClass]="{'shrink': shouldShrink(a.category1, a.category2), 'showAll': section == 'allwork' }">{{a.listing}}</div>
And inside the component:
section = 'allwork';
shouldShrink(cat1, cat2) {
return this.section === cat1 || this.section === cat2 ? false : true;
}
Here I need to calculate if i should shrink a div based on if a 2 different categories have matched what the selected category is. And it works. So from there you can computer a true/false for the [ngClass] based on what your method returns given the inputs.
There are multiple ways to write same logic. As it mentioned earlier, you can use object notation or simply expression. However, I think you should not that much logic in HTML. Hard to test and find issue. You can use a getter function to assign the class.
For Instance;
public getCustomCss() {
//Logic here;
if(this.x == this.y){
return 'class1'
}
if(this.x == this.z){
return 'class2'
}
}
<!-- HTML -->
<div [ngClass]="getCustomCss()"> Some prop</div>
//OR
get customCss() {
//Logic here;
if(this.x == this.y){
return 'class1'
}
if(this.x == this.z){
return 'class2'
}
}
<!-- HTML -->
<div [ngClass]="customCss"> Some prop</div>
Source: Stackoverflow.com