The Built-in `NgSwitch` Directive

Let’s learn about `NgSwitch`, a built-in attribute directive.

The NgSwitch structural directive provides another well-known switch keyword to the HTML world. We can treat it as an extension of the NgIf directive, which helps consider multiple cases.

The NgSwitch syntax

The NgSwitch syntax is very similar to switch syntax from other languages. So, we have a place that takes an expression, the particular cases, and a default value if no case fits.

Based on this, we can distinguish three directives composed of the NgSwitch feature.

  • The plain attribute directive NgSwitch is in control of other directives.
  • The structural directive NgSwithCase adds or removes elements from the DOM if its bound value equals the expression value.
  • The structural directive NgSwitchDefault adds an element to the DOM when none of the present cases are met.

Below, let’s consider such a component by breaking the template and class into separate snippets:

@Component({
  selector: 'app-weather',
  templateUrl: './weather.component.html',
})
export class WeatherComponent {
	 @Input() forecast: 'sun' | 'rain' | 'cloud' | 'snow'; 
}

The code above has a property called forecast that can store one of four string values. If we want to present a different view based on the actual forecast, we could use multiple NgIf statements. However, it’s pointless to do that when we could use NgSwitch, which is far more readable in this case.

<section [ngSwitch]="forecast">
	<p *ngSwitchCase="'sun'"> 🌤️ </p>
	<p *ngSwitchCase="'rain'"> 🌧️ </p>
	<p *ngSwitchCase="'cloud'"> ☁️ </p>
	<p *ngSwitchCase="'snow'"> 🌨️ </p>
	<p *ngSwitchDefault> 🌈 </p>
</section>

The template is not very complicated, although it contains all three directives. So, first things first, the ngSwitch directive is set on the container element and bound to the forecast component’s property. The component’s property could be a function that returns the value, object, or anything else we want to use. Then, we implement a template for each case we want to support (in this example, all cases).

Each template has a *ngSwitchCase directive with an assigned specific value. If the result of the ngSwitch bound value is the same as the one in *ngSwitchCase, the provided template is added to the DOM. The last step is to supply an optional *ngSwitchDefault.

Get hands-on with 1200+ tech skills courses.