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

@switch

Pick by value.

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

When one value decides between several fixed choices, like a book's format, at switch reads more clearly than a chain of at else if.

  • One value
  • Several fixed choices
  • @switch

The @switch block

At switch takes a value. Each at case compares it with one choice. The first matching case is shown. And at default shows when no case matches.

keyvalue
@switch (value)the value to check
@case ('ebook')one choice
First matchshown
@defaultwhen nothing matches

Formats

Format is a signal, starting as paperback. Three buttons set it. At switch reads the format, and each case shows a different message. Audio has no case, so default handles it. We click ebook. Run it. The ebook message shows.

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

@Component({
  selector: 'app-root',
  template: `
    <button (click)="format.set('paperback')">Paperback</button>
    <button id="ebook" (click)="format.set('ebook')">Ebook</button>
    <button (click)="format.set('audio')">Audio</button>
    @switch (format()) {
      @case ('paperback') { <p>Delivered in 2 days, £2.99 postage.</p> }
      @case ('ebook') { <p>Download instantly, no postage.</p> }
      @default { <p>Coming soon in this format.</p> }
    }
  `,
})
export class App {
  format = signal('paperback');
}
Also uses actions.json
[{"click": "#ebook"}]

Summary

At switch picks one case by value, with at default as the fallback. Next, at let.

Key takeaways
  • @switch (format())
  • @case
  • @default
Next up: @let — local names in templates