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
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.