Angular: Conditional Class with *ngClass

The NgClass directive allows you to set the CSS class dynamically for a DOM element. There are two ways to use this directive,

1. The first is by passing an object literal to the directive

[ngClass]="{'your_class_name': true}"

When using an object literal, the keys are the classes that 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 onto the element the directive is attached to. Refer is the example,

[ngClass]="{ 'text-success': country === 'UK', 
'text-primary': country === 'USA', 
'text-danger': country === 'HK' }"

We can also set a class on an element by binding to the input property binding called class , like


If we want just to add the list of classes already set on the element, we can use the following extended syntax


following is the best example with multiple class binding

[class.text-success]=" === 'UK'" 
[class.text-primary]=" === 'USA'" 
[class.text-danger]=" === 'HK'"

Subscribe for
weekly updates