InterviewHubPRO
Section Overview
Q205

Question 205 of 283

Part 8: Internationalization (i18n), Testing & DOM Directives (177 - 212)

72%
Angular & Signals (283 Qs)•Part 8: Internationalization (i18n), Testing & DOM Directives (177 - 212)

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:

html
<!-- 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:

html
<!-- 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

FeatureClassic [ngSwitch] DirectivesModern @switch Built-in Block
ImportsRequires CommonModule, NgSwitch, NgSwitchCase, NgSwitchDefault⚡ Zero imports required
Container ElementRequires a host DOM element (e.g., <div> or <ng-container>)No container element needed
Type CheckingLoose type checking on case valuesStrict type narrowing across branches
PerformanceThree separate directive instances per caseSingle optimized compiler instruction