FrontEndTech
  • Introduction
  • ReactJS
    • Ecosystem
    • Refactor Using Functional Decomposition and Reducer Composition
  • AngularJS
    • installation
    • File structure
    • CLI
      • ng g
    • Fundamentals
      • Component
        • Lifecycle
        • Template
      • Decorations
      • Service
      • Pipe
      • Directives
        • NgClass
        • NgStyle
        • NgModel
        • Customized Attribute Directives
        • NgIf
        • NgFor
        • NgSwitch
        • NgForm
        • Customized Structural Directives
      • Module
        • Routing
    • Bindings
      • Property Binding
      • Event Binding
      • Data Binding
      • Attribute Binding
      • Class Binding
      • Style Binding
    • Forms
      • Reactive Form
      • Reactive vs Template
    • build
Powered by GitBook
On this page

Was this helpful?

  1. AngularJS
  2. Bindings

Class Binding

PreviousAttribute BindingNextStyle Binding

Last updated 5 years ago

Was this helpful?

  • 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 is usually preferred when managing multiple class names at the same time.

NgClass directive