Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngClass multiple ternary operator conditions

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

like image 396
d-_-b Avatar asked Jun 13 '15 21:06

d-_-b


People also ask

Can ternary operator have 3 conditions?

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.

Can you have multiple ternary operators?

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.

Can we use ternary operator in ngClass?

'css-class-1' : 'css-class-2' . So ngClass still can use ternary operator in Angular 2.

Can I use multiple ngClass?

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.


1 Answers

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')"
like image 81
sfletche Avatar answered Oct 13 '22 12:10

sfletche