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'"
Method 2
[ngClass]="{'my_class': step === 'step1'}"
Method 3
[ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"
Method 4
[ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"
Method 5
[ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"
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>
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.