AI Hints
Home›Angular Tutorial›track, @empty and @switch
Angular · Lesson 41 of 120

@empty

When the list is empty.

⏱ 2 min read▶ Video at 49:53🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Sometimes a list is empty. No search results, or an empty basket. The page should say so, instead of showing nothing.

  • Empty lists happen
  • Say so
  • @empty

The @empty block

At empty comes right after the at for block. Its content shows only when the list has no items. When items arrive, it disappears again. It saves writing a separate at if.

keyvalue
Placedright after @for { }
Showswhen the list is empty
Hideswhen items arrive
Savesa separate @if

Search with no results

Every key press stores the text in the query signal. Found is computed, the books whose title contains the query. At for lists them, and at empty explains when nothing matches. We type, z, z. Run it. No title contains z z, so the empty message shows.

app.tstypescript
import { Component, signal, computed } from '@angular/core';
import { BOOKS } from './books';

@Component({
  selector: 'app-root',
  template: `
    <input placeholder="Search" (input)="query.set($any($event.target).value)">
    @for (book of found(); track book.id) {
      <p>{{ book.title }}</p>
    } @empty {
      <p class="muted">No books match "{{ query() }}".</p>
    }
  `,
})
export class App {
  query = signal('');
  found = computed(() =>
    BOOKS.filter(b => b.title.toLowerCase().includes(this.query().toLowerCase())));
}
Also uses books.ts
export interface Book {
  id: number;
  title: string;
  author: string;
  price: number;
  stock: number;
}

export const BOOKS: Book[] = [
  { id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99, stock: 4 },
  { id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien', price: 8.99, stock: 0 },
  { id: 3, title: 'Circe', author: 'Madeline Miller', price: 10.99, stock: 2 },
  { id: 4, title: 'Emma', author: 'Jane Austen', price: 6.99, stock: 7 },
  { id: 5, title: 'Persuasion', author: 'Jane Austen', price: 7.49, stock: 1 },
];
Also uses actions.json
[{"type": "input", "text": "zz"}]

Summary

At empty shows its content when the at for list has no items. Next, at switch.

Key takeaways
  • @for { } @empty { }
  • No results message
  • Disappears with items
Next up: @switch — pick by value