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

Administrator Access Granted.
Standard User Privileges.
Guest Access (Read-only).
Unknown Role. Please contact support.

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