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:



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.


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.


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';  


Tom is Pressed
Joy is Selected
Default Option