Class Binding

  • You can add and remove CSS class names from an element's class attribute with a class binding.

Just add [class.some-css-class]="some-condition" to the element you want to style.

Angular adds the class when the template expression evaluates to truthy. It removes the class when the expression is falsy.

[class.selected]="hero === selectedHero"

When the current row hero is the same as the selectedHero, Angular adds the selected CSS class. When the two heroes are different, Angular removes the class.

  • You can replace that with a binding to a string of the desired class names; this is an all-or-nothing, replacement binding.

<!-- reset/override all class names with a binding  -->
<div class="bad curly special" [class]="badCurly">Bad curly</div>

While this is a fine way to toggle a single class name, the NgClass directive is usually preferred when managing multiple class names at the same time.

Last updated

Was this helpful?