Posted by Arjun on Monday 14th August 2017

Angular NgSwitch Directive

The NgSwitch directive lets you to insert different sets of elements into the document based on a specified value or expression.NgSwitch Directive resides inside CommonModule module, so you can import it as shown below

 import { NgSwitch } from '@angular/common';

[caption id="attachment_5297" align="aligncenter" ]Angular NgSwitch Directive [/caption]

How to use NgSwitch

In the below code, we are getting iterating over the items objects, to show the status of the current item we are using [ngSwith] expression.

<table class="table table-striped table-bordered">    
    <thead>        
        <tr><th></th><th>Description</th><th>Done</th></tr>   
    </thead>    
    <tbody>        
        <tr *ngFor="let item of items; let i = index"> 
            <td>{{ i + 1 }}</td>            
            <td>{{ item.action }}</td>            
            <td [ngSwitch]="item.done">                
                <span *ngSwitchCase="true">Yes</span>               
                <span *ngSwitchDefault>No</span>            
            </td>        
        </tr>   
    </tbody> 
</table>

In the above example based on item.done property value, the nested span elements will be added to DOM.