What is NgSwitch in Angular [Step-by-step Guide]

Angular ngSwitch directive on the container specifies an expression to match against. The ngSwitchCase directives on views within the container provide the expressions to match.

  1. Every view that matches is rendered.
  2. The view with a ngSwitchDefault directive is rendered if there are no matches.
  3. Elements within the [NgSwitch] statement but outside of any NgSwitchCase or ngSwitchDefault directive are preserved at the location.

Define the container element for the directive and specify a switch expression to match against an attribute.

<container-element [ngSwitch]="switch_expression">

Within the container, *ngSwitchCase statements specify the match expressions as attributes.

Include *ngSwitchDefault as a final case.

<container-element [ngSwitch]="switch_expression">
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
    ...
  <some-element *ngSwitchDefault>...</some-element>
</container-element>

Selector

[ngSwitch]

Properties

Property Description
@Input()
ngSwitch: any
Write-Only

Example: How to Implement NgSwitch Directive in Angular

Let’s say we wanted to display show names in different colors depending on where they are streaming.

With a bootstrap framework, we can change the text color using text-danger, text-success, text-warning, and text-primary classes.

We could solve this by having the series of *ngIf statements, like so,

<ul *ngFor="let show of shows">
 <li *ngIf="show.service ==='Netflix'"
 class="text-success">{{ show.name }} ({{ show.name }})
 </li>
 <li *ngIf="show.service === 'Disneyplus'"
 class="text-primary">{{ show.name }} ({{ show.name }})
 </li>
 <li *ngIf="show.service === 'HBOMax'"
 class="text-danger">{{ show.name }} ({{ show.country }})
 </li>
 <li *ngIf="show.service !== 'HBOMax' && person.country !== 'Netflix' && person.country !== 'Disneyplus'"
 class="text-warning">{{ show.name }} ({{ show.country }})
 </li>
</ul>

This initially seems to make sense until we create the other style item.

Here is the step-by-step guide to implementing NgSwitch Directive in Angular.

Step 1: Install the Angular project

Type the following command.

ng new angular-ngswitch

When you install a brand new Angular project, see the options they provide while creating a new one. For example, we need the routing module to allow the Angular CLI to generate a routing module for us in this project.

I use Visual Studio Code as a programming editor to develop Angular applications.

Now, go inside the folder and open the project inside the VSCode.

Step 2: Write demo data in an app.component.ts file

Write the following code inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  shows: any[] = [
    {
      name: 'Stranger Things',
      service: 'Netflix',
    },
    {
      name: 'The Mandalorian',
      service: 'Disneyplus',
    },
    {
      name: 'Game of Thrones',
      service: 'HBOMax',
    },
    {
      name: 'Amazon Prime',
      service: 'Fleabag',
    }
  ];
}

In the above code, we have added an array of objects to use in an angular switch statement.

Step 3: Write a view app.component.html file.

<div class="container">
  <h4>NgSwitch Example</h4>
  <ul *ngFor="let show of shows" [ngSwitch]="show.service">
    <li *ngSwitchCase="'Netflix'" class="text-success">{{ show.name }} ({{ show.service }})
    </li>
    <li *ngSwitchCase="'Disneyplus'" class="text-primary">{{ show.name }} ({{ show.service }})
    </li>
    <li *ngSwitchCase="'HBOMax'" class="text-danger">{{ show.name }} ({{ show.service }})
    </li>
    <li *ngSwitchDefault class="text-warning">{{ show.name }} ({{ show.service }})
    </li>
  </ul>
</div>

Let’s see the following output.

 

ngswitch Directive In Angular

The NgSwitch case in the above example is just an example and isn’t efficient in solving this problem. This is a demo and practical example of using it in our regular project.

We would use either the NgStyle or NgClass directives for the above example.

Using NgIf, we can conditionally add or remove an element from the DOM.

If we face multiple conditions, a cleaner alternative to multiple nested NgIf statements is the NgSwitch series of directives.

Let’s remove some of the properties of the object of the show.

Write the following code inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  shows: any[] = [
    {
      name: 'The Mandalorian',
      service: 'Disneyplus',
    }
  ];
}

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.