Home  >  Angular

Angular 2 NgSwitch Example

By Arvind Rai, November 16, 2016
On this page we will provide angular 2 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. 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. 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.

Software Used

Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.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 TypeScript 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 into template

Angular expands *ngSwitchCase and *ngSwitchDefault into template. First angular expands *ngSwitchCase and *ngSwitchDefault into template directive and <template> tag.
Using asterisk we do as follows.
<b *ngSwitchCase="dirEnum.South">South Direction</b>
<b *ngSwitchDefault>No Direction</b> 
1. Expand into template directive.
<b template = "ngSwitchCase:dirEnum.South">South Direction</b>
<b template = "ngSwitchDefault">No Direction</b> 
Find the complete code using ngSwitch
<div [ngSwitch]="myDir">
  <b template = "ngSwitchCase:dirEnum.East"> East Direction</b>
  <b template = "ngSwitchCase:dirEnum.West"> West Direction</b>  
  <b template = "ngSwitchCase:dirEnum.North">North Direction</b>
  <b template = "ngSwitchCase:dirEnum.South">South Direction</b>
  <b template = "ngSwitchDefault">No Direction</b>
</div> 
2. Expand into <template> tag.
<template [ngSwitchCase]= "dirEnum.South"> <b>South Direction</b> </template>
<template ngSwitchDefault> <b> No Direction</b> </template> 
Find the complete code using ngSwitch
<div [ngSwitch]="myDir">
  <template [ngSwitchCase]= "dirEnum.East"> <b> East Direction</b> </template>
  <template [ngSwitchCase]= "dirEnum.West"> <b> West Direction</b> </template>
  <template [ngSwitchCase]= "dirEnum.North"> <b>North Direction</b> </template>
  <template [ngSwitchCase]= "dirEnum.South"> <b>South Direction</b> </template>
  <template ngSwitchDefault> <b> No Direction</b> </template>
</div> 
In this way if we do not want to use asterisk (*) we can use template directive or <template> tag for ngSwitchCase and ngSwitchDefault. Here we can understand that ngSwitch does not define content. It only controls a collection of templates. That is why angular does not add asterisk (*) as prefix with ngSwitch .

Complete Example using TypeScript


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: 'app/person.component.html', 
    styleUrls: ['app/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">
  <b template = "ngSwitchCase:dirEnum.East"> East Direction</b>
  <b template = "ngSwitchCase:dirEnum.West"> West Direction</b>  
  <b template = "ngSwitchCase:dirEnum.North">North Direction</b>
  <b template = "ngSwitchCase:dirEnum.South">South Direction</b>
  <b template = "ngSwitchDefault">No Direction</b>
</div>

<div [ngSwitch]="myDir">
  <template [ngSwitchCase]= "dirEnum.East"> <b> East Direction</b> </template>
  <template [ngSwitchCase]= "dirEnum.West"> <b> West Direction</b> </template>
  <template [ngSwitchCase]= "dirEnum.North"> <b>North Direction</b> </template>
  <template [ngSwitchCase]= "dirEnum.South"> <b>South Direction</b> </template>
  <template ngSwitchDefault> <b> No Direction</b> </template>
</div> 
person.component.css
.one {
    color: green;
}
.two {
    color: red;
} 
module.ts
import {NgModule}         from '@angular/core';
import {BrowserModule}    from '@angular/platform-browser';
import {PersonComponent}  from './person.component';
@NgModule({
  imports:      [BrowserModule],
  declarations: [PersonComponent],
  bootstrap:    [PersonComponent]
})
export class AppModule { } 
main.ts
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);  
index.html
<html>
  <head>
    <title>Angular 2 Demo</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('myApp').catch(function(err){ console.error(err); });
    </script>
  </head>
  <body>
    <person-app>Please Wait...</person-app>
  </body>
</html> 

Run Application

Find the steps to run the example.
1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.
2. Download the source code using download link given below in the example.
3. Go to the root folder of the project using command prompt and run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.
Angular 2 NgSwitch Example

Reference

ANGULAR 2 TEMPLATE SYNTAX: NgSwitch

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us