Understanding NgSwitchCase Directive and NgSwitch In Angular

NgSwitchCase directive along with its parent NgSwitch block enables you to decide which view to display when the expression is evaluated dynamically. When a given property in the app.component file can have different possible values and based upon those values, our HTML template has to change, we can use NgSwitchCase and NgSwitch in such requirement.

Syntax Of NgSwitchCase Directive

The syntax for NgSwitchCase directive is to wrap ngSwitch in brackets and then bind it to a property. Then for each possible values of that property, you bind a ngSwitchCase element with a desired View. If the given SwitchCase is true, it will show the element in the DOM.

Syntax For NgSwitchCase Directive
Syntax For NgSwitchCase Directive

Demo

Let’s create a property called “key” in our app.component file.

key = "state";
In the HTML template, add the following:
<div [ngSwitch] ="key">

<p *ngSwitchCase="'state'">State: Louisiana </p>

<p *ngSwitchCase="'city'">Lake Charles</p>

<p *ngSwitchCase="'country'">USA</p>

</div>
Now, fire up your terminal to load the Angular app into your browser and you should be able to see a view similar to this one as below:
ngSwitch Demo
ngSwitch Demo

If you change the value of “key” to “city”, in your view, you should see that it is now loading the paragraph element for:

<p *ngSwitchCase="'city'">Lake Charles</p>

As you can see, NgSwitchCase Directive can be very useful to show dynamic views to the user. Whenever a value of property is changed, the view that is rendered to the user can get dynamically updated.

What happens when there is no matching value in the ngSwitchCase?

When there is no matching ngSwitchCase directive, nothing will be shown in the View. However, if you want to display a default template when there are no matching value for your property, in such case you can make use of ngSwitchCaseDefault.

<p *ngSwitchDefault>...</p>
So, the default template is used whenever there are no matching values in the ngSwichCase directive.