Angular : conditional class with *ngClass

Rajesh Kumar Yadav - May 14 '21 - - Dev Community

What is NgClass?

Adds and removes CSS classes on an HTML element.

Angular provides several ways to add classes conditionally:

Method 1

[class.my_class] = "step === 'step1'"
Enter fullscreen mode Exit fullscreen mode

Method 2

[ngClass]="{'my_class': step === 'step1'}"
Enter fullscreen mode Exit fullscreen mode

Method 3

[ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"
Enter fullscreen mode Exit fullscreen mode

Method 4

[ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"
Enter fullscreen mode Exit fullscreen mode

Method 5

[ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"
Enter fullscreen mode Exit fullscreen mode

Based on the Official Documentation

The CSS classes are updated as follows, depending on the type of the expression evaluation:

string - the CSS classes listed in the string (space delimited) are added,
Array - the CSS classes declared as Array elements are added,
Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

<some-element [ngClass]="'first second'">...</some-element>

<some-element [ngClass]="['first', 'second']">...</some-element>

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
Enter fullscreen mode Exit fullscreen mode

Buy Me A Coffee

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .