Directivesbeginner
New Control Flow with the @switch Block
Explain the @switch block as the built-in replacement for ngSwitch and its comparison semantics.
@switch is the built-in control flow replacement for the [ngSwitch]/*ngSwitchCase/*ngSwitchDefault trio of structural directives, and it exists for the same reasons @if and @for do: native compiler support, no imports required, and a cleaner syntax for a very common pattern — rendering one of several mutually exclusive branches based on a single value.
It's like a hotel front desk sorting guests into exactly one queue lane based on their reservation type — VIP, standard, or walk-in — nobody stands in two lanes, and there's a designated overflow lane (@default) for anything that doesn't match a known category.
Key Concepts
1
Interviewers like asking about the comparison semantics specifically: @switch uses strict equality (===), same as ngSwitch did, which matters when switching on values that might be loosely-equal-but-not-identical (like 0 and false, or numeric strings versus numbers) — a subtle bug source if you're not careful about the type of the switch expression versus the case expressions.
@switch===ngSwitch0false
2
Structurally, a @switch block contains one or more @case blocks and an optional @default block, and unlike a JavaScript switch statement, there's no fallthrough between cases — each @case is a fully separate, non-cascading branch, which actually makes it safer and easier to reason about than the language-level switch it superficially resembles.
@switch@case@defaultswitch
3
A reasonable follow-up question is when to prefer @switch over a chain of @if/@else if: @switch communicates "these are mutually exclusive branches of one value" more clearly to a reader, while @if/@else if chains are better when each branch tests a genuinely different, unrelated condition rather than the same expression against different values.
@switch@if@else if