A class binding controls whether an element belongs to one named CSS class. Write `[class.className]="expression"` when a condition should add or remove that class without replacing the element’s other classes. section 11.4.1
Mark the selected category
A category button can keep its base classes while gaining `active` only when it represents the selected category: `<button class="btn btn-outline-primary" [class.active]="cat == selectedCategory()" (click)="changeCategory(cat)">{{cat}}</button>`. The click binding changes the selection; the class binding gives visual feedback. section 5.5.2
Class bindings also respond to state changed by other events. In a product table, a `mouseover` binding updates a selection signal, and `[class.bg-info]="getSelected(item)"` highlights the matching row. Angular reevaluates the class-binding expression as application state changes. section 13.2
Choose the binding that matches the scope of the change:
- Use `[class.name]` to control one class while retaining existing classes. section 11.4.1
- Use `[class]` when an expression supplies the entire required class string; it replaces previous class memberships. section 11.4.1
- Use `ngClass` when a map controls membership of multiple classes. section 11.4.1
Listing 11.12. Using the special class binding in the template.html file in the src/app folder
<div class="text-white">
<div [class]="getClasses(0)">
The first product is {{ products()[0].name }}
</div>
<div class="p-2"
[class.bg-success]="(products()[1].price ?? 0) < 50"
[class.bg-info]="(products()[1].price ?? 0) >= 50">
The second product is {{products()[1].name}}
</div>
</div>
The template keeps `p-2` on a product element and uses separate class bindings to select a background class from its price. section 11.4.1
