Angular: Apply Classes Conditional
May 10, 2023
In this article, we will explore a few options for conditionally applying a class to an element in Angular.
Apply based on a condition
In cases where you want to apply a class if a condition is met otherwise not apply it, you can use the syntax:
[class.className]="condition"
The example below applies the “warning” class if weatherWarning is not ‘No Warning’.
[class.warning]="weatherWarning != 'No Warning'"
Apply either of two based on a condition
In cases where you want to apply one class or another based on a condition, you can use the syntax:
[ngClass]="condition ? 'class1' : 'class2'"
The example below applies the “no-warning” class if weatherWarning is ‘No Warning’ otherwise the “warning” class.
[ngClass]="weatherWarning == 'No Warning' ? 'no-warning' : 'warning'"
Apply any number of classes based on separate conditions
In cases where you want to apply any number of classes based on a set of conditions, you can use the syntax:
[ngClass]="{ 'class1': condition1, 'class2': condition2, ... }"
The example below will apply:
- “cold” if temp <= 10
- No classes if temp is between 10 and 20
- “hot” if temp <= 20
- “hot” and “very-hot” if temp > 35
[ngClass]="{ 'cold': temp <= 10, 'hot': temp >= 20, 'very-hot': temp > 35 }"