ngSwitch Directive

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

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

    In Angular ngSwitchCase directive, the inner elements are placed inside the container element. The ngSwitchCase directive is applied to the inner elements with a match expression. Whenever the value of the match expression matches the value of the switch expression, the corresponding inner element is added to the DOM. All other inner elements are removed from the DOM

    If there is more than one match, then all the matching elements are added to the DOM.

    ngSwitchDefault

    You can also apply the ngSwitchDefault directive in Angular 8. The element with ngSwitchDefault is displayed only if no match is found. The inner element with ngSwitchDefault can be placed anywhere inside the container element and not necessarily at the bottom. If you add more than one ngSwitchDefault directive, all of them are displayed.

    Any elements placed inside the container element, but outside the ngSwitchCase or ngSwitchDefault elements are displayed as it is.

    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> 

        Comments

        Leave a Reply

        Your email address will not be published. Required fields are marked *