DEV Community

Blake Lamb
Blake Lamb

Posted on

Intro To The [ngSwitch] Directive

Overview

Have you ever come upon a situation where you need to conditionally show more than two different variations of content based on one variable? A situation where *ngIf - else doesn't work without nesting *ngIf's? In this article I'll give an example that will help solve that problem in a much more readable way than nesting *ngIf statements.

Setup - Create A Sandbox App

Go to Stackblitz and start a new "Angular" project. Or you can fork my Stackblitz here to allow you to follow along with my example.

*ngIf - else

Angular has the ability to conditionally show content by using the *ngIf directive. This also has the option to add an "else" to effectively show a default as well. If the statement inside the *ngIf evaluates to false. An example of this might look like:

<p *ngIf="selectedOption; else noneSelected">
  You've chosen too see option {{ selectedOption }}
</p>
<ng-template #noneSelected>
  <p>Please select an option!</p>
</ng-template>
Enter fullscreen mode Exit fullscreen mode

This would show the text "You've chosen to see option {{ selectedOption }}" if selectedOption evaluates to truthy. Otherwise it would display "Please select an option!". This directive is extremely useful, but if there are more than two options to be displayed, it requires an *ngIf to be nested within one another. This method of conditionally showing content can be difficult to keep straight logically and sacrifices readability of the code.

The [ngSwitch] Directive

In a situation where you may want to conditionally show more than two options, using the [ngSwitch] directive works great! This directive will work just like a switch statement in JavaScript, and will allow as many cases as are needed. The syntax is to put [ngSwitch]="switch_expression" on the containing element, then put *ngSwitchCase="match_expression" on each element that is a separate case. Additionally, an element can be the default element by adding *ngSwitchDefault in place of the *ngSwitchCase. An example of this could look like this:

<div [ngSwitch]="selectedOption">
  <p *ngSwitchDefault>This is the default that you're seeing!</p>
  <p *ngSwitchCase="1">You're now seeing Variation 1!</p>
  <p *ngSwitchCase="2">You're now seeing Variation 2!</p>
  <p *ngSwitchCase="3">You're now seeing Variation 3!</p>
  <p *ngSwitchCase="4">You're now seeing Variation 4!</p>
</div>
Enter fullscreen mode Exit fullscreen mode

This allows any number of options to be possibly displayed, while also keeping simplicity and doesn't sacrifice readability.

Conclusion

Solutions that increase readability and simplicity are always great tools to have. Utilizing this directive in your daily development will help you achieve both of those goals and improve your Angular Skills. Check out my example below and let me know what you think!

Latest comments (0)