I am trying to combine the following two ng-class
ternary expressions into one ng-class
(so I can control both the color, via btn-success/danger classes, and the width, via width-small/medium/wide class, of my button divs
<div class="btn" ng-class="(rate > 0) ? 'btn-success' : 'btn-danger'">{{rate}}</div>
<div class="btn" ng-class="(priority == 'low') ? 'width-small' : (priority == 'medium') ? 'width-medium' : 'width-wide'">{{rate}}</div>
I realize I could just do something along the lines of below; however, I would like to make use of the ternary expressions available in 1.1.5
<div class="btn" ng-class="{'btn-success': rate > 0, 'btn-danger': rate <= 0, 'width-small': priority == 'low', 'width-medium': priority == 'medium', 'width-wide': prioity == 'high'}">{{rate}}</div>
Space separating the expressions did not work for me, nor did comma separating them within ng-class
Thanks advance for your assistance in determining if/how to have multiple ternary expressions in a single ng-class
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.
Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : c.
'css-class-1' : 'css-class-2' . So ngClass still can use ternary operator in Angular 2.
Ternary operators can be nested just like if-else statements. Consider the following code: int a = 1, b = 2, ans; if (a == 1) { if (b == 2) { ans = 3; } else { ans = 5; } } else { ans = 0; } printf ("%d\n", ans); Here's the code above rewritten using a nested ternary operator: int a = 1, b = 2, ans; ans = (a == 1 ? (
For anyone looking for the answer: Yes this is indeed possible, also as mentioned the readability is questionable.
<div ng-class="(conversation.read ? 'read' : 'unread') + ' ' + (conversation.incoming ? 'in' : 'out')"></div>
From the ngClass documentation:
The directive operates in three different ways, depending on which of >three types the expression evaluates to:
If the expression evaluates to a string, the string should be one or >more space-delimited class names.
If the expression evaluates to an array, each element of the array >should >be a string that is one or more space-delimited class names.
If the expression evaluates to an object, then for each key-value pair of >the object with a truthy value the corresponding key is used as a class >name.
Option 1 applies here.
From my understanding using this method will result in 2 watches while using object notation will result in 4, but I might be wrong on this one.
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