Angular ngClass multiple ternary operator conditions
25,604
Solution 1
While I totally agree with @SamuelMS about explicitly displaying your class names...
If you really want to use multiple ternary operators (or are simply curious) you can do so like this:
ng-class="($index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium') + ' ' + (true ? 'red' : 'blue')"
Solution 2
My preferred syntax for ng-class is the following, since it is explicit as to which classes you are adding.
ng-class={ 'className' : yourConditionHere, 'class2' : anotherConditionHere }
Give that a try.
Comments
-
d-_-b about 4 years
What is the best way to put more than 1 ternary conditional class in angular's
ngClass
directive, where the values are the class-names?I've tried a few variations on this, but i always get a compiling error:
ng-class="$index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium', true ? 'red':'blue'
ng-class="{$index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium', true ? 'red':'blue'}
-
d-_-b almost 9 yearsThanks, I was looking to see if there is a way to have the class names as the values of the ternary operators.
-
d-_-b almost 9 yearshaha, that's a nice approach. I can definitely see why @SamuelMS approach is better but this is helpful, thanks!