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