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
[ngSwitch]: Applied to a container element. Defines the expression whose value will be evaluated.*ngSwitchCase: Applied to elements within the container. Renders the element if its value matches the[ngSwitch]expression.*ngSwitchDefault: Applied to an element within the container. Renders if none of the*ngSwitchCaseconditions 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.