`ngClass` is an Angular directive for managing an element’s CSS class memberships through a one-way binding. In `<div [ngClass]="classes()">`, Angular evaluates `classes()` and uses its result to add or remove classes on the `div`. If the component’s signal returns `bg-success` when the data model contains five objects and `bg-warning` otherwise, the background class follows that condition. section 11.2
Choose the binding that matches the classes you need to manage:
- `[class]="expr"` replaces existing class memberships with the classes returned by the expression. Use it when that expression supplies every required class. section 11.4.1
- `[class.bg-success]="expr"` manages one named class according to the expression. Use it for individual classes without replacing the others. section 11.4.1
- `[ngClass]="expr"` accepts a space-separated string, an array of class names, or an object whose property names specify classes and whose truthy values enable them. An object property name can contain multiple space-separated classes. section 11.4.1
Keep a fixed class while selecting a background
A product element can keep `class="p-2"` and bind `[ngClass]="{'bg-success': (products()[2].price ?? 0) < 50, 'bg-info': (products()[2].price ?? 0) >= 50}"`. The expression selects a background class from the product’s price while `p-2` remains in the template. The same example also passes class-map objects returned by a component method to `ngClass`. section 11.4.1
Keep template expressions simple. Concatenating fixed classes with a component value is possible—for example, `'text-white p-2 ' + classes()`—but complex retrieval and processing logic belongs in the component or model, where it can be compiled and tested. section 11.2.2
Table 11.7. The expression result types supported by the ngClass directive
|
Name
|
Description
|
|
String
|
The host element is added to the classes specified by the string. Multiple classes are separated by spaces.
|
|
Array
|
Each object in the array is the name of a class that the host element will be added to.
|
|
Object
|
Each property on the object is the name of one or more classes, separated by spaces. The host element will be added to the class if the value of the property is truthy.
|
Use the result-type table to check whether a class expression should return a string, array, or object. section 11.4.1
