Blog>
Snippets

Handling Empty Lists with ngFor and ngIf

Implement ngFor to render a list and use ngIf to display a 'No items' message when the list is empty.
import { Component } from '@angular/core';

@Component({
  selector: 'app-item-list',
  template: `
    <ul *ngIf="items.length > 0; else noItemsTemplate">
      <li *ngFor="let item of items">{{ item }}</li>
    </ul>
    <ng-template #noItemsTemplate>No items</ng-template>
  `
})
export class ItemListComponent {
  items: string[] = [];

  // Method to populate the items list
  addItems() {
    this.items = ['Item 1', 'Item 2', 'Item 3'];
  }

  // Method to clear the items list, triggering the 'No items' message
  clearItems() {
    this.items = [];
  }
}
Angular component with an item list rendered using ngFor and a message displayed using ngIf when the list is empty. The 'items' array is initialized as an empty array. The 'addItems()' method can be used to populate the list, while the 'clearItems()' method will clear the list and trigger the 'No items' message.