ngSwitch
ngSwitch is a structural directive in Angular that provides a way to add or remove DOM elements based on an expression. It is similar to the switch statement in many programming languages and is used for displaying one of several possible views based on a given condition. This directive is particularly useful for situations where you have multiple conditions that might lead to different UI elements being displayed.
How It Works
-
[ngSwitch]:-- This directive is placed on a container element. It takes an expression that evaluates to a value. This value is then compared with the values provided byngSwitchCasedirectives. -
*ngSwitchCase:-- This directive is used on the elements inside thengSwitchcontainer. It marks a block of HTML that will be rendered if the expression provided matches thengSwitchexpression. -
*ngSwitchDefault:-- This directive is optional and is used to display a block of HTML when none of thengSwitchCaseconditions are met.
Syntax and Usage
Here's how you would typically use ngSwitch in a template:
<div [ngSwitch]="expression">
<div *ngSwitchCase="value1">Content for value1</div>
<div *ngSwitchCase="value2">Content for value2</div>
<!-- more cases as needed -->
<div *ngSwitchDefault>Default content</div>
</div>
In this structure:
expressionis evaluated and compared against the values inngSwitchCasedirectives.- If a match is found, the corresponding block (e.g.,
Content for value1) is displayed. - If no match is found, the block marked with
*ngSwitchDefaultis displayed.
Example
Consider an application where you want to display different messages based on a user's role:
<div [ngSwitch]="user.role">
<div *ngSwitchCase="'admin'">Welcome, admin user!</div>
<div *ngSwitchCase="'guest'">Welcome, guest!</div>
<div *ngSwitchCase="'member'">Hello, member!</div>
<div *ngSwitchDefault>Welcome, user!</div>
</div>
In this example:
- The
user.roleexpression is evaluated. - Depending on its value, one of the
ngSwitchCaseblocks will be displayed. Ifuser.roleis'admin', the first block is shown; if'guest', the second, and so on. - If
user.roledoesn't match any of the cases, thengSwitchDefaultblock is displayed.
More examples
Below are various examples demonstrating different use cases and features of ngSwitch:
Basic Use of ngSwitch
-
Simple Conditional Display: Show different content based on the value of a variable.
<div [ngSwitch]="userType">
<div *ngSwitchCase="'admin'">Admin View</div>
<div *ngSwitchCase="'user'">User View</div>
<div *ngSwitchDefault>Guest View</div>
</div>Here, depending on the value of
userType, either the admin, user, or guest view will be displayed.
Handling Enums and Constants
-
Using Enums or Constants: Useful for when you have predefined types or constants.
export enum UserType {
Admin,
User,
Guest
}<div [ngSwitch]="currentUser.type">
<div *ngSwitchCase="userTypes.Admin">Admin</div>
<div *ngSwitchCase="userTypes.User">User</div>
<div *ngSwitchDefault>Guest</div>
</div>currentUser.typeis compared against the values fromUserTypeenum.
Handling Component States
-
Component States: Managing different states of a component (e.g., loading, content, error).
<div [ngSwitch]="dataState">
<app-loading *ngSwitchCase="'loading'"></app-loading>
<app-content *ngSwitchCase="'loaded'"></app-content>
<app-error-message *ngSwitchCase="'error'"></app-error-message>
<app-empty *ngSwitchDefault></app-empty>
</div>Different components are displayed based on the current data state.
Multiple Cases with the Same Content
-
Grouping Multiple Cases: Sometimes, you might want to display the same content for different cases.
<div [ngSwitch]="notification.type">
<p *ngSwitchCase="'info'">Information Message</p>
<p *ngSwitchCase="'success'">Success Message</p>
<p *ngSwitchDefault>Error or Warning Message</p>
</div>Here, both error and warning notifications use the same default message.
Dynamic Component Templates
-
Dynamic Templates: Use
ngSwitchto dynamically swap templates or components.<ng-container [ngSwitch]="layoutType">
<app-grid-view *ngSwitchCase="'grid'"></app-grid-view>
<app-list-view *ngSwitchCase="'list'"></app-list-view>
<app-map-view *ngSwitchDefault></app-map-view>
</ng-container>This allows for a dynamic user interface where the layout type can be switched.
Nested ngSwitch
-
Nested
ngSwitch: You can nestngSwitchdirectives for more complex conditional logic.<div [ngSwitch]="primaryCondition">
<div *ngSwitchCase="'A'">
<div [ngSwitch]="secondaryCondition">
<div *ngSwitchCase="'1'">A1 view</div>
<div *ngSwitchCase="'2'">A2 view</div>
</div>
</div>
<div *ngSwitchCase="'B'">B view</div>
<div *ngSwitchDefault>Default view</div>
</div>This example uses a nested
ngSwitchfor a secondary level of condition checking.
Use in Forms
-
Form Input Types: Dynamically render different form controls based on data types.
<div [ngSwitch]="field.type">
<input *ngSwitchCase="'text'" type="text">
<input *ngSwitchCase="'number'" type="number">
<select *ngSwitchCase="'select'"></select>
<input *ngSwitchDefault type="text">
</div>
Best Practices
- Use for Multiple Conditions:--
ngSwitchis best used when you have more than two conditions to handle. For a single condition,ngIfmight be more appropriate. - Simplicity:-- Keep the switch expression and cases simple for readability and maintainability.
- Performance:-- While
ngSwitchcan be more performant than multiplengIfstatements in some cases, consider the complexity of your templates and the frequency of changes to the switch expression.