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.
Let’s create a property called “key” in our app.component file.
key = "state";
<div [ngSwitch] ="key"> <p *ngSwitchCase="'state'">State: Louisiana </p> <p *ngSwitchCase="'city'">Lake Charles</p> <p *ngSwitchCase="'country'">USA</p> </div>
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.