Angular ngClass multiple ternary operator conditions

27.8k views Asked by At

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'}

3

There are 3 answers

1
sfletche On

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')"
1
SamuelMS On

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.

0
Hamfri On

If you are working on angular 8+ the following should work.

[ngClass]="{'css-class' : condition1 === true || condition2 === true }">