Angular ngSwitch Directive

In this Angular ngSwitch Directive article, we’ll see how can we use ngSwitch directive in angular application.

ngSwitch is a structural directive that adds or removes templates when the next match expression matches the switch expression.


Using ngSwitch

ngSwitch is used to display one element from a set of elements based on the condition.  

ngSwitch also contains a related structural directive as follows:  

ngSwitch: It specifies an expression to match against.  
ngSwitchCase: It specifies the element for matched expression.  
ngSwitchDefault: If specifies the element and will be displayed if there is no match for the expression.


Example

Let’s take an example of a grading system where we’ll show a message based on the grade that students got.  


<ul [ngswitch]="grade">  
  <li *ngswitchcase="'A'">Excellent</li>
  <li *ngswitchcase="'B'">Very Good</li>
  <li *ngswitchcase="'C'">Good</li>
  <li *ngswitchcase="'D'">Average</li>
  <li *ngswitchcase="'E'">Low</li>
  <li *ngswitchdefault="">Invalid Grade</li>
</ul>

In the above example,

if the value of grade is A then only li tag with the value A will be included in the DOM.
and if the value grade will not be matched with any ngSwitchCase then li tag with ngSwitchDefault will be included in the DOM.


I hope you like this Angular ngSwitch Directive article. 🙂

Also Read: