Skip to main content

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 by ngSwitchCase directives.

  • *ngSwitchCase:-- This directive is used on the elements inside the ngSwitch container. It marks a block of HTML that will be rendered if the expression provided matches the ngSwitch expression.

  • *ngSwitchDefault:-- This directive is optional and is used to display a block of HTML when none of the ngSwitchCase conditions 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:

  • expression is evaluated and compared against the values in ngSwitchCase directives.
  • If a match is found, the corresponding block (e.g., Content for value1) is displayed.
  • If no match is found, the block marked with *ngSwitchDefault is 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.role expression is evaluated.
  • Depending on its value, one of the ngSwitchCase blocks will be displayed. If user.role is 'admin', the first block is shown; if 'guest', the second, and so on.
  • If user.role doesn't match any of the cases, the ngSwitchDefault block is displayed.

More examples

Below are various examples demonstrating different use cases and features of ngSwitch:

Basic Use of ngSwitch

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

  1. 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.type is compared against the values from UserType enum.

Handling Component States

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

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

  1. Dynamic Templates: Use ngSwitch to 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

  1. Nested ngSwitch: You can nest ngSwitch directives 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 ngSwitch for a secondary level of condition checking.

Use in Forms

  1. 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:-- ngSwitch is best used when you have more than two conditions to handle. For a single condition, ngIf might be more appropriate.
  • Simplicity:-- Keep the switch expression and cases simple for readability and maintainability.
  • Performance:-- While ngSwitch can be more performant than multiple ngIf statements in some cases, consider the complexity of your templates and the frequency of changes to the switch expression.