1. Introduction
In this short tutorial we are going to present several ways to add a class
for HTML element conditionally in Angular.
2. Ways to add class
conditionally in Angular
- using
class.other_class
statement:
[class.other_class] = "step === 'step1'"
- using
ngClass
:
[ngClass]="{'other_class': step === 'step1'}"
- using
ngClass
with multiple options:
[ngClass]="{'other_class': step === 'step1', 'other_class2' : step === 'step2'}"
- using multiple conditions:
[ngClass]="{'other_class': property1.isValid && !property2.isValid}"
- using method expression:
[ngClass]="getSomeClass()"
getSomeClass() {
const isValid=this.property1 && !this.property2;
return {
someClass1:isValid,
someClass2:isValid
};
}
- using ternary operator:
[ngClass]="step == 'step1' ? 'other_class1' : 'other_class2'"
3. More about ngClass
directive
In Angular ngClass
directive is used to add or remove classes
on HTML elements. This means if some element has a class
attribute, the [ngClass]
directive will add another class
or classes
while rendering the view.
<div class="some_class" [ngClass]="'other_class'"></div>
This will be rendered as:
<div class="some_class other_class"></div>
The [ngClass]
directive supports the following value types:
string
- CSS class or classes separated with space are added to HTML element,<html-element [ngClass]="'first second'">...</html-element>
Array
- all CSS classes declared as Array elements are added using space separator,<html-element [ngClass]="['first', 'second']">...</html-element>
Object
Map - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.<html-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</html-element>
4. Conclusion
In this article we showcased several ways to add class
to element conditionally in Angular.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}