Back to course

Built-in Structural Directives: *NgSwitch

The Complete Angular Developer: From Zero to Hero

17. Built-in Structural Directives: *NgSwitch

*NgSwitch is Angular's way of implementing conditional rendering based on multiple potential values, similar to a JavaScript switch statement.

It removes elements from the DOM just like *NgIf.

NgSwitch Directives Trio

  1. [ngSwitch]: Applied to a container element. Defines the expression whose value will be evaluated.
  2. *ngSwitchCase: Applied to elements within the container. Renders the element if its value matches the [ngSwitch] expression.
  3. *ngSwitchDefault: Applied to an element within the container. Renders if none of the *ngSwitchCase conditions are met.

*NgSwitch Example

Component Class:

typescript export class NotificationComponent { userRole: string = 'admin'; // 'guest', 'user', or 'admin'

promoteToAdmin() { this.userRole = 'admin'; } }

Template:

html <button (click)="promoteToAdmin()">Promote</button>

<div [ngSwitch]="userRole"> <div *ngSwitchCase="'admin'" class="badge-admin"> Administrator Access Granted. </div> <div *ngSwitchCase="'user'" class="badge-user"> Standard User Privileges. </div> <div *ngSwitchCase="'guest'"> Guest Access (Read-only). </div> <!-- Rendered if userRole is anything else (e.g., 'pending') --> <div *ngSwitchDefault> Unknown Role. Please contact support. </div> </div>

*NgSwitch is clearer and often more performant than chaining multiple *NgIf/else statements, especially when comparing against a single variable.