Blog>
Snippets

Conditional Class Binding with ngFor and ngIf

Combine ngFor and ngIf to apply a class conditionally on list items based on their properties.
/* Component's HTML Template */
<ul>
  <li *ngFor="let item of items" 
      [class.special-item]="item.isSpecial" 
      *ngIf="item.isVisible">
    {{ item.name }}
  </li>
</ul>
Iterates over the 'items' array and creates a list item for each element. The 'special-item' class is applied conditionally if the 'item.isSpecial' property is true, and the item is only included in the DOM if 'item.isVisible' is true.
/* Component's TS file snippet */
// Define the items array with properties
items = [
    { name: 'Item 1', isSpecial: true, isVisible: true },
    { name: 'Item 2', isSpecial: false, isVisible: true },
    { name: 'Item 3', isSpecial: true, isVisible: false },
    // more items...
];
Defines an 'items' array in the component's Typescript file. Each item has a 'name', a boolean 'isSpecial' indicating if it should receive the class, and a 'isVisible' indicating if it should be displayed.
/* CSS Stylesheet */
.special-item {
  font-weight: bold;
  color: green;
}
Defines the CSS for the 'special-item' class, which will be applied conditionally in the template.