Home >>Angular8 Tutorial >Angular8 ngSwitch Directive

Angular8 ngSwitch Directive

Angular8 ngSwitch Directive

NgSwitch is a structural directive in Angular 8 that is used to add / remove DOM Element. It is identical to the C # switch statement. The ngSwitch directive has a switch expression applied to the container element.

Syntax of ngSwitch


<container_element [ngSwitch]="switch_expression">  
<inner_element *ngSwitchCase="match_expresson_1">...</inner_element>  
<inner_element *ngSwitchCase="match_expresson_2">...</inner_element>  
<inner_element *ngSwitchCase="match_expresson_3">...</inner_element>  
<inner_element *ngSwitchDefault>...</element>  
</container_element>   

ngSwitchCase

The inner elements are put inside the container element in the Angular ngSwitchCase directive. The ngSwitchCase directive is implemented with a match expression on the inner elements. Whenever the match expression value matches the switch expression value, the corresponding inner element is added to the DOM. All other inner components are removed off the DOM.

If more than one match occurs then all matching elements are applied to the DOM.

ngSwitchDefault

In Angular 8, you can apply the ngSwitchDefault directive too. The element with ngSwitchDefault is only shown if there is no match. The inner element with ngSwitchDefault can be put anywhere inside and not necessarily at the bottom of the container. If you add more than one directive ngSwitchDefault, it will show all of these.

Any elements that are placed inside the container but outside the ngSwitchCase or ngSwitchDefault elements are shown as they are.

ngSwitch Directive Example

Use the following code in app.component.ts file of your application:


class item {  
    name: string;  
    val: number;  
}  
export class AppComponent  
{  
    items: item[] = [{name: 'One', val: 1}, {name: 'Two', val: 2}, {name: 'Three', val: 3}];  
    selectedValue: string= 'One';  
}  

Use the following code in the app.component.html file of your application:


<select [(ngModel)]="selectedValue">  
<option *ngFor="let item of items;" [value]="item.name">{{item.name}}</option> </select>  
<div class='row' [ngSwitch]="selectedValue">  
<div *ngSwitchCase="'One'">One is Pressed</div>  
<div *ngSwitchCase="'Two'">Two is Selected</div>  
<div *ngSwitchDefault>Default Option</div>  
</div>  


No Sidebar ads