Angular ngSwitch directive example

Angular *ngSwitch Directive

In this 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.


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>

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.

Also Read:

Leave a Comment