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'}
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
But what if we are to use multiple if-else statements? Such issues can be tackled using multiple ternary operators in a single statement. In the above syntax, we have tested 2 conditions in a single statement using the ternary operator.
'css-class-1' : 'css-class-2' . So ngClass still can use ternary operator in Angular 2.
Overview. You can use the ngClass directive to conditionally apply one-to-many classes or styles to an element, giving you an effective way to operate with multiple classes or styles at once.
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')"
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