@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
@casecompares it using strict equality,===. So'5'does not match5, and'Bright'does not match'bright'. - Only the matching case renders. There is no fall-through and no
breakto write, unlike a JavaScriptswitch. @defaultrenders 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.
The value
status()returns'ok','soon'or'overdue'.
Drills
Answer fast — trust the rule.
How does @case compare its value with the switch value?
level() returns the number 2. Which case matches?
Two cases both precede @default, and the first one matches. What renders?
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, nobreak. - Trap: mismatched types or spelling; list the exact values first, then add
@default.
