Home  >  Angular

Angular NgSwitch Example

By Arvind Rai, January 01, 2021
On this page we will provide Angular NgSwitch example. NgSwitch is an Angular directive that displays one element from a possible set of elements based on some condition. NgSwitch uses NgSwitchCase and NgSwitchDefault directive. NgSwitch uses ngSwitchCase keyword to define a set of possible element trees and ngSwitchDefault is used to define default value when expression condition does not match to any element tree defined by ngSwitchCase. The NgSwitch is used as property binding such as [ngSwitch] with bracket [ ]. To define possible set of elements, we need to add asterisk (*) as prefix to the switch case keywords as *ngSwitchCase and *ngSwitchDefault. Whenever NgSwitch finds a match evaluated by expression then the respective element defined by ngSwitchCase is added to DOM and if no match is found then the element defined by ngSwitchDefault is added to DOM. Here on this page we will provide example of NgSwitch with NgFor as well as NgClass using TypeScript. We will also provide the example for how to use TypeScript enum with NgSwitch.


Technologies Used

Find the technologies being used in our example.
1. Angular 11.0.3
2. Node.js 12.5.0
3. NPM 6.9.0

Using NgSwitch

NgSwitch is a directive which is bound to an expression. NgSwitch is used to display one element tree from a set of many element trees based on some condition. It uses three keywords as follows.

ngSwitch: We bind an expression to it that returns the switch value. It uses property binding.

ngSwitchCase: Defines the element for matched value. We need to prefix it with asterisk (*).

ngSwitchDefault: Defines the default element when there is no match. We need to prefix it with asterisk (*).

Find the code snippet for NgSwitch with bracket [ ].
<ul [ngSwitch]="person">
  <li *ngSwitchCase="'Mohan'">Hello Mohan</li>
  <li *ngSwitchCase="'Sohan'">Hello Sohan</li>
  <li *ngSwitchCase="'Vijay'">Hello Vijay</li>
  <li *ngSwitchDefault>Bye Bye</li>
</ul>  
Here ngSwitch has been assigned with expression person which is a property in component having value "Sohan". So in our switch case the below line of code will run.
<li *ngSwitchCase="'Sohan'">Hello Sohan</li>  
If person gives a value which does not match to any of the ngSwitchCase then element with ngSwitchDefault will be executed.

NgSwitch with NgFor and NgClass

Find the code snippet which is using NgSwitch with NgFor and NgClass. Here NgSwitch is using interpolation {{ }}.
<div *ngFor="let id of ids">
  Id is {{id}}
  <div ngSwitch="{{id%2}}">
	<div *ngSwitchCase="'0'" [ngClass]="'one'">I am Even.</div>
	<div *ngSwitchCase="'1'" [ngClass]="'two'">I am Odd.</div>
	<div *ngSwitchDefault>Nothing Found.</div>
  </div> 	
</div>  
Here ids is an array defined in component which has numbers. For each iteration we are getting array element in the variable id. Now we are using this variable in ngSwitch and dividing it by 2. For 0 value the element with CSS class .one will be executed and for 1 the element with CSS class .two will be executed.

NgSwitch with Enum

Here we will discuss how to use NgSwitch with enum. Suppose we have an enum as below. directionEnum.ts
export enum DirectionEnum {
    East, West, North, South 
}  
Now we need to import this enum in our component as follows.
import {DirectionEnum} from './directionEnum';  
In our component class we will assign our DirectionEnum to a component property as below.
dirEnum = DirectionEnum;  
Here dirEnum is a component property that will be used to access enum values. Hence we are ready to use enum in our angular HTML template as follows.
<div [ngSwitch]="myDir">
  <b *ngSwitchCase="dirEnum.East">East Direction</b>
  <b *ngSwitchCase="dirEnum.West">West Direction</b>
  <b *ngSwitchCase="dirEnum.North">North Direction</b>
  <b *ngSwitchCase="dirEnum.South">South Direction</b>
  <b *ngSwitchDefault>No Direction</b>
</div>  
Here myDir is a component property and this will assign the value to ngSwitch. For example if we assign it as
myDir = DirectionEnum.North;  
Then the following line of code will execute.
<b *ngSwitchCase="dirEnum.North">North Direction</b>  

Expanding ngSwitchCase and ngSwitchDefault with ng-template

Angular expands ngSwitchCase and ngSwitchDefault with ng-template directive as following.
<div [ngSwitch]="myDir">
  <ng-template [ngSwitchCase]= "dirEnum.East"> <b> East Direction</b> </ng-template>
  <ng-template [ngSwitchCase]= "dirEnum.West"> <b> West Direction</b> </ng-template>
  <ng-template [ngSwitchCase]= "dirEnum.North"> <b>North Direction</b> </ng-template>
  <ng-template [ngSwitchCase]= "dirEnum.South"> <b>South Direction</b> </ng-template>
  <ng-template ngSwitchDefault> <b> No Direction</b> </ng-template>
</div> 

Complete Example

directionEnum.ts
export enum DirectionEnum {
    East, West, North, South 
}  
person.component.ts
import { Component } from '@angular/core';
import { DirectionEnum } from './directionEnum';
@Component({
    selector: 'person-app',
    templateUrl: './person.component.html',
    styleUrls: ['./person.component.css']
})
export class PersonComponent {
    person = 'Sohan';
    ids = [1, 2, 3, 4];
    dirEnum = DirectionEnum;
    myDir = DirectionEnum.North;
} 
person.component.html
<ul [ngSwitch]="person">
  <li *ngSwitchCase="'Mohan'">Hello Mohan</li>
  <li *ngSwitchCase="'Sohan'">Hello Sohan</li>
  <li *ngSwitchCase="'Vijay'">Hello Vijay</li>
  <li *ngSwitchDefault>Bye Bye</li>
</ul>

<div *ngFor="let id of ids">
  Id is {{id}}
  <div ngSwitch="{{id%2}}">
	<div *ngSwitchCase="'0'" [ngClass]="'one'">I am Even.</div>
	<div *ngSwitchCase="'1'" [ngClass]="'two'">I am Odd.</div>
	<div *ngSwitchDefault>Nothing Found.</div>
  </div> 	
</div>

<div [ngSwitch]="myDir">
  <b *ngSwitchCase="dirEnum.East"> East Direction</b>
  <b *ngSwitchCase="dirEnum.West"> West Direction</b>
  <b *ngSwitchCase="dirEnum.North">North Direction</b>
  <b *ngSwitchCase="dirEnum.South">South Direction</b>
  <b *ngSwitchDefault>No Direction</b>
</div>

<div [ngSwitch]="myDir">
  <ng-template [ngSwitchCase]= "dirEnum.East"> <b> East Direction</b> </ng-template>
  <ng-template [ngSwitchCase]= "dirEnum.West"> <b> West Direction</b> </ng-template>
  <ng-template [ngSwitchCase]= "dirEnum.North"> <b>North Direction</b> </ng-template>
  <ng-template [ngSwitchCase]= "dirEnum.South"> <b>South Direction</b> </ng-template>
  <ng-template ngSwitchDefault> <b> No Direction</b> </ng-template>
</div> 
person.component.css
.one {
    color: green;
}
.two {
    color: red;
} 
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
		<person-app></person-app>
             `
})
export class AppComponent {
}  
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { PersonComponent } from './person.component';

@NgModule({
    imports: [
        BrowserModule
    ],
    declarations: [
        AppComponent,
        PersonComponent
    ],
    providers: [
    ],
    bootstrap: [
        AppComponent
    ]
})
export class AppModule { } 

Run Application

To run the application, find the steps.
1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200
Find the print screen of the output.
Angular NgSwitch Example

References

NgSwitch Directive
NgSwitchCase Directive
NgSwitchDefault Directive

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI








©2021 concretepage.com | Privacy Policy | Contact Us