'Using ternary operator in HTML to decide on the class to be implemented
I want to decide on a CSS class dynamically using ternary operator in HTML. I'm using following code but it seems the condition isn't being evaluated at all. Whatever class that is written in the true part of the condition, is applied. How can I apply a particular class based on some condition? Any alternative approach will be helpful too.
<td class="col-md-6"><span class="form-control-static cdr-details-td" />
<span class="(('1' === '-1') ? version-modal-header : failure)">{{cdr.causeCode}}</span>
</td>
CSS for the same:
.version-modal-header {
background-color: #000000;
}
.failure {
color: #ff0000;
font-weight: bold;
}
Solution 1:[1]
Use ng-class instead
ng-class="{'version-modal-header': condition, 'failure': !condition}"
You can also use a ternary if you want
ng-class="condition ? 'version-modal-header' : 'failure'"
Solution 2:[2]
Please check working example here : Example
Use ng-class
ng-class="{true: 'version-modal-header', false: 'failure'}[changeClass]"
You can write your conditions in [changeClass]
Solution 3:[3]
The ternary operation that you have incorporated in your program, doesn't works for class or to be specific - HTML DOM. It can be done using AngularJS, as it provides a wonderful inbuilt directive knows as ng-class. Using this one can set the conditions, based on which one needs to apply the class.
Have a look at the snippet below:
<td class="col-md-6"><span class="form-control-static cdr-details-td" />
<span ng-class="{'version-modal-header': '1' === '-1', 'failure': '1' === '1'}">{{cdr.causeCode}}</span>
</td>
Check out the demo here.
Solution 4:[4]
Use ng-class if you want to apply a css class dynamically. dont use interpolation or binding {{}} to apply css class directly as it will not work across browsers.
In ng-class you just need to specify an object containing class names as keys and the respective Boolean condition as values. Any class whose value evaluates to true is applied dynamically.
<td class="col-md-6"><span class="form-control-static cdr-details-td" />
<span ng-class="{'version-modal-header':('1' === '-1') , 'failure': ('1' !== '-1')}">{{cdr.causeCode}}</span>
</td>
Solution 5:[5]
you can use it to show and hide content dynamically
{{condition ? 'value if true' : 'value if false'}}
Solution 6:[6]
Heres a solution that worked for me.
<p style={{borderBottom: loginToggle ? '6px solid blue' : "None"}}></p>
Solution 7:[7]
if you looking for ternary operator in style attribute in .net view pages then following answer will work for you.
style ="background-color: @(Model.IsVisible ? "#fde0e0;" : "#DFF0D8;")"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | User2 |
| Solution 3 | Shashank |
| Solution 4 | Rahul Malu |
| Solution 5 | |
| Solution 6 | luneth777 |
| Solution 7 | Rahul Vaity |
