Angular *ngSwitch Directive

Angular *ngSwitch Directive

Angular ngSwitch Directive Example

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 set of elements based on the condition.

ngSwitch also contains 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 grade system where we’ll show a message based on the grade that student got.
&lt;ul [ngSwitch]="grade"&gt;<br />  &lt;li *ngSwitchCase="'A'"&gt;Excellent&lt;/li&gt;<br />  &lt;li *ngSwitchCase="'B'"&gt;Very Good&lt;/li&gt;<br />  &lt;li *ngSwitchCase="'C'"&gt;Good&lt;/li&gt;<br />  &lt;li *ngSwitchCase="'D'"&gt;Average&lt;/li&gt;<br />  &lt;li *ngSwitchCase="'E'"&gt;Low&lt;/li&gt;<br />  &lt;li *ngSwitchDefault&gt;Invalid Grade&lt;/li&gt;<br />&lt;/ul&gt;  

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