liveBook · Manning

Class binding

As explained in Pro Angular 16

A special class binding is Angular syntax that independently controls whether a named CSS class is present on an element.

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

How Pro Angular 16 covers it

How deep it goes
Explains the syntax and individual-class behavior through templates, but does not examine binding internals.
Examples
Shows an active category button, price-dependent product backgrounds, and a highlighted product-table row.
What it assumes
Assumes familiarity with template expressions and CSS classes while showing class-binding syntax directly.
What you can do after
Apply it via Angular templates to toggle one CSS class without replacing an element’s existing classes.
How it connects
Connects class binding to property binding, ngClass, event binding, signals, and change detection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.