How to use NgClass in angular?
NgClass
When using an object literal, the keys are the classes which are added to the element if the value of the key evaluates to true.
So in the above example, since the value is true this will set the class text-success onto the element the directive is attached to.
The value can also be an expression, so we can
[ngClass]="{'text-success':person.country === 'UK'}"
Let’s implement the colored names demo app using ngClass
<h4>NgClass</h4>
<ul *ngFor="let person of people">
<li [ngClass]="{
'text-success':person.country === 'UK',
'text-primary':person.country === 'USA',
'text-danger':person.country === 'HK'
}">{{ person.name }} ({{ person.country }})
</li>
</ul>
Since the object literal can contain many keys we can also set many class names.
We can now color our text with different colors for each country with one statement.
If we run the above code we would see:
Alternative Syntax
We can also set a class on an element by binding to the input property binding called class, like so [class]="'text-success'"
<ul *ngFor="let person of people">
<li [class.text-success]="person.country === 'UK'"
[class.text-primary]="person.country === 'USA'"
[class.text-danger]="person.country === 'HK'">{{ person.name }} ({{ person.country }})
</li>
</ul>

Comments
Post a Comment