# Angular 8 ngSwitch Directive

The ngSwitch in Angular 8 is a structural directive that is similar to the switch statement of C#. Being used to Add/Remove DOM Element, this directive is applied to the container element with a switch expression.

Syntax of Angular 8 ngSwitch Directive:

<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:

Being applied to the inner elements with a match expression, the inner elements in the Angular ngSwitchCase directive are placed inside the container element. The corresponding inner element whose value of the switch expression matches the value of the match expression is added to the DOM, while the rest inner elements are removed from the DOM. All the matching elements are added to the DOM, in case there is more than one match.

### ngSwitchDefault:

The ngSwitchDefault directive can also be applied in Angular 8, where the element with ngSwitchDefault is displayed in case no match is found. The inner element with ngSwitchDefault need not necessarily placed at the bottom and can be placed anywhere inside the container element. In case more than one ngSwitchDefault directive is added, all of them are displayed. The elements that are placed outside the ngSwitchCase or ngSwitchDefault elements but inside the container element are displayed as it is.

Example: Angular 8 ngSwitch Directive:

Add the below codes to the app.component.ts and app.component.html files respectively.

app.component.ts:

class item { name: string; id: number; } export class AppComponent { items: item[] = [{name: 'Tom', id: 101}, {name: 'Joy', id: 102}, {name: 'Smith', id: 103}]; selectedValue: string= 'Tom'; }

app.component.html:

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