What is the purpose of ngSwitch directive?
The ngSwitch directive conditionally swaps DOM elements based on a matching expression, functioning like a JavaScript switch statement. Angular supports both the Classic Built-in Directives (ngSwitch, *ngSwitchCase, *ngSwitchDefault) and the Modern Built-in Control Flow (@switch, @case, @default).
1. Classic Built-in Directives: ngSwitch
Classic ngSwitch requires a parent container with the [ngSwitch] property binding, combined with *ngSwitchCase and *ngSwitchDefault structural directives on child elements:
<!-- Classic ngSwitch syntax (requires CommonModule or NgSwitch import) -->
<div [ngSwitch]="userRole">
<admin-dashboard *ngSwitchCase="'admin'" [user]="currentUser"></admin-dashboard>
<moderator-panel *ngSwitchCase="'moderator'" [user]="currentUser"></moderator-panel>
<editor-view *ngSwitchCase="'editor'" [user]="currentUser"></editor-view>
<standard-user-view *ngSwitchDefault [user]="currentUser"></standard-user-view>
</div>
2. Modern Built-in Control Flow: @switch (Angular 17+)
The modern @switch block eliminates the need for wrapper HTML elements, provides cleaner indentation, and supports strict type narrowing:
<!-- Modern Built-in Control Flow syntax (Angular 17+) -->
@switch (userRole) {
@case ('admin') {
<admin-dashboard [user]="currentUser" />
}
@case ('moderator') {
<moderator-panel [user]="currentUser" />
}
@case ('editor') {
<editor-view [user]="currentUser" />
}
@default {
<standard-user-view [user]="currentUser" />
}
}
3. Key Differences: Classic vs Built-in @switch
| Feature | Classic [ngSwitch] Directives | Modern @switch Built-in Block |
|---|---|---|
| Imports | Requires CommonModule, NgSwitch, NgSwitchCase, NgSwitchDefault | ⚡ Zero imports required |
| Container Element | Requires a host DOM element (e.g., <div> or <ng-container>) | No container element needed |
| Type Checking | Loose type checking on case values | Strict type narrowing across branches |
| Performance | Three separate directive instances per case | Single optimized compiler instruction |