3. Use the ngClass directive in the HTML template.
We’ll categorize students based on their grades, different grades will have different colors.
ngClass accepts string, array, object, map, set, function, and binding to a CSS class. we’ll use all of them in the following examples.
1. String syntax
Note, since ngClass is a property binding, we need to wrap the class name in '' to make it a hard-coded string, otherwise the class name will be treated as a variable in your component.
1
<div [ngClass]="'grade-A'">Student A</div>
ngClass is commonly used to bind a variable in component, for example, we can define a variable grade in the component, and bind it to the ngClass directive.
1
grade = 'grade-A';
1
<div [ngClass]="grade">Student A</div>
If you want to apply a class without a condition, you can simply use the following syntax.
With any object-like bindings such as Array, Object, Map, and Set syntax, the identity of the object must change for Angular to apply the new class. Updating the property without changing the identify has no effect, for example:
This one doesn’t work, because gradeObject is the same object.
1
this.gradeObject["grade-b"] = false;
This one works, because gradeObject is a new object.
[ngClass] is a directive that allows you to add or remove classes based on conditions, while [class] is a property binding that allows you to add a class without a condition.
Most of the above case can be achieved by [class] as well, except the following case.