Today we will understand the last built in directive provided by the Angular Team -
<container-element [ngSwitch]="switchExpression"> <child-element *ngSwitchCase="matchExpression.1"> content </child-element> <child-element *ngSwitchCase="matchExpression.N"> content </child-element> <child-element *ngSwitchDefault> content </child-element> </container-element>
ngSwitch is placed inside a container element like
div. We need to assign a switchExpression to the
ngSwitch using property binding syntax (
The switch-expression value is evaluated at runtime by Angular and accordingly displays or removes elements from the DOM.
ngSwitchCase is placed in an inner child element, which is placed inside the
container-element. If you have noticed we use * in front of ngSwitchCase because its a structural directive. We also assign a match expression which is evaluated at runtime.
The child-element is displayed only if the
match expression and
switch expression matches, else it will be removed from DOM.
ngSwitchCase does not hide the element, but it removes them from the DOM
ngSwitchDefault is also placed in an inner child element which must be placed inside the container element. An important thing to note is it DOES NOT have any match expression. If none of the ngSwitchCase match expression matches the switch expression then the default is is shown.
We can add
ngSwitchDefault anywhere inside the container element (not necessary at the very end)
We can add as many
ngSwitchDefault as we want. If none of the condition matches all the default elements will be displayed.
ngSwitchDefault is also a directive.
Now lets see how the ngSwitch directive actually works.
Lets open the component template file -
and paste in the below code-
<ul [ngSwitch]="color"> <li *ngSwitchCase="'1'">RED</li> <li *ngSwitchCase="'2'">GREEN</li> <li *ngSwitchCase="'3'">BLUE</li> <li *ngSwitchCase="'4'">ORANGE</li> <li *ngSwitchDefault>RAINBOW</li> </ul>
and now lets open the component.ts file and add the
color variable and assign a value say 1 to it.
color = 1;
Now, once you run the application and open your browser in localhost:4200 you should see the below output
Now if you change the value of the color variable to say 20 which is not present in the matchExpression you should see the output as RAINBOW.
You should try to use 2 ngSwitchDefault in your code and check for the output.
Hope you enjoyed the post, if yes please do like and comment.
Stay tuned for more Angular topics.