Angular ngClass Usage

If we are working on an Angular application, then we get into a situation where we need to apply CSS classes dynamically to HTML elements.

This can be achieved using the directive ngClass in Angular in any of the ways mentioned below.

Method 1

In the below example, the class highlight is applied only when the condition step === 'step1' is evaluated to be true, otherwise ignored.

[class.my_class] = "step === 'step1'"

Method 2

Using Angular directive ngClass as shown below.

[ngClass]="{'my_class': step === 'step1'}"

and multiple options

[ngClass]="{'my_class1': step === 'step1', 'my_class2' : step === 'step2' }"

Method 3

[ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class3'}[step]"

Method 4

Using a conditional operator to determine the class to apply.

[ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"

Overall

We can use the Angular directive ngClass to apply CSS classes dynamically to the HTML elements.