[AngularJs] NgClass Directive If-Else Expression

Usage: <ANY ng-class="expression">...</ANY> where "expression" is: "Expression to eval. The result of the evaluation can be a string representing space delimited class names, an array, or a map of class names to boolean values. In the case of a map, the names of the properties whose values are truthy will be added as css classes to the element." [Official doc]

So let's see some examples...

Set class if condition

Set a class if the valued expression is true.

Code:

<input id="check1" type="checkbox" ng-model="checkCondition" /> <label for="check1">SetCondition</label><br />

<span ng-class="{'text-danger': checkCondition}">Text</span>

Result:


Text

Set class if else condition (Ternary operation)

Set a class if the valued expression is true or another if the condition is false.

Code:

<input id="check2" type="checkbox" ng-model="checkCondition2" /> <label for="check2">checkCondition2</label><br />

<span ng-class="(checkCondition2) ? 'text-danger' : 'text-success'">Text</span>

Result:


Text

Set class multi conditions

Set different classes each one with his own condition

Code:

<input id="check3" type="checkbox" ng-model="checkDanger" /> <label for="check3">Set danger</label><br />
<input id="check4" type="checkbox" ng-model="checkBold" /> <label for="check4">Set bold</label><br />
<input id="check5" type="checkbox" ng-model="checkItalic" /> <label for="check5">Set italic</label><br />

<span ng-class="{'text-danger': checkDanger, 'font-weight-bold': checkBold, 'font-italic': checkItalic}">Text</span>

Result:




Text