Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

@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.

The shortcut

Before writing a @switch, list the exact values the thing can hold, spelled and typed exactly as they are in the data. Each becomes a @case. Then ask "what if it is something else?" and write a @default for it.

Showing a watering badgeStep 1 of 4
  1. The value

    status() returns 'ok', 'soon' or 'overdue'.

Drills

Answer fast — trust the rule.

quick drill

How does @case compare its value with the switch value?

quick drill

level() returns the number 2. Which case matches?

quick drill

Two cases both precede @default, and the first one matches. What renders?

quick drill

Which situation suits @switch better than @if?

Remember

  • @switch (value) { @case (x) { } @default { } }, built in, no imports.
  • Strict === match, first hit only, no fall-through, no break.
  • Trap: mismatched types or spelling; list the exact values first, then add @default.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainLight needs

Each Greenhouse plant has light set to 'bright', 'medium' or 'low'. Write a @switch that shows a different tip for each value and a fallback for anything else, then explain how Angular chooses the case and why you might pick @switch over a chain of @else if.