Skip to the workspace
Pebellslearn by building
Template Syntax and Lifecycle  ›  Lesson

@switch, @case and @default

@switch 12 minThe @switch block compares one value against each @case using strict equality, renders only the matching case, and falls back to @default, with no fall-through between cases.

angular / @switch, @case and @default

Explore each scene at your own pace.

01 · The rule

The rule

@switch, @case and @default

Each plant in Greenhouse has a light need: 'bright', 'medium' or 'low'. The care panel shows a different tip for each. You could write three @else if branches that each repeat plant().light === ..., but when one value picks between fixed options, there is a clearer tool.

The rule

One value, many cases, strict match, first hit only.

@switch (plant().light) {
  @case ('bright') {
    <p>Put it near your sunniest window.</p>
  }
  @case ('medium') {
    <p>A few steps back from the window is ideal.</p>
  }
  @case ('low') {
    <p>A shady corner suits it fine.</p>
  }
  @default {
    <p>We are not sure yet. Watch its leaves.</p>
  }
}
  • @switch (value) evaluates the value once.
  • Each @case compares it using strict equality, ===. So '5' does not match 5, and 'Bright' does not match 'bright'.
  • Only the matching case renders. There is no fall-through and no break to write, unlike a JavaScript switch.
  • @default renders when no case matches. It is optional; without it, nothing renders for unmatched values.

Like @if, it is built in: no imports. It replaces the older trio of [ngSwitch], *ngSwitchCase and *ngSwitchDefault.

When to choose which:

  • @switch: one value, compared with several fixed options.
  • @if / @else if: different conditions, ranges (count() > 5) or tests on different values.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.