Class Binding

Add additional classes to an element dynamically, based on some condition, for example, here when we want to apply the active class on this button based on the state of the underlying component.

If this condition is true, this target class will be added to this element. Otherwise if it’s false and this class exists on the element, it will be removed.

Use class and style bindings to add and remove CSS class names from an element’s class attribute and to set styles dynamically.

Interface

export interface User {
  firstName: string,
  lastName: string,
  isActive?: boolean
}

Mock

this.users = [
    {
      firstName: 'John',
      lastName: 'Doe',
      isActive: true
    },
    {
      firstName: 'Kevin',
      lastName: 'Johnson',
      isActive: false
    }
  ];

HTML

<div class="card" 
    *ngFor="let user of users" 
    [class.bg-light]="user.isActive" 
    [style.border-color]="user.isActive ? 'green' : ''">
    <h3 [ngStyle]="currentStyles">
        {{ user.firstName }} {{ user.lastName }}
    </h3>
</div>
Was this page helpful?