Angular 10 Tutorial - ngSwitch Directive

In this tutorial, we will learn about the ngSwitch Directive in Angular 10. The directive on a container specifies an expression to match against. The expressions to match are provided by directives on views within the container. Every view that matches is rendered. If there are no matches, a view with the directive is rendered.

Using ngSwitch Directive in Angular 10

So, let's see how we can use the ngSwitch Directive in Angular 10. Switch to the project and go to the app.component.html file and write the following code:


<div [ngSwitch]="color">
<div class="red box" *ngSwitchCase="'red'">
<p>Red Color</p>
</div>
<div class="green box" *ngSwitchCase="'green'">
<p>Green Color</p>
</div>
<div class="blue box" *ngSwitchCase="'blue'">
<p>Blue Color</p>
</div>
<div class="default box" *ngSwitchDefault>
<p>Default Color</p>
</div>
</div>

Now, let's create some CSS classes. Go to the app.component.css file:


.box{
height:200px;
width:200px;
text-align:center;
border:1px solid;
}
.red{
background-color:red;
}
.green{
background-color:green;
}
.blue{
background-color:blue;
}
.default{
background-color:#fff;
}

Now, let's check it. So, switch to the browser and here you see the green square. If we change the color to red, you can see here the color is red. If we change the color to blue, the color is blue. And if we change the color to grey, which is not in the switch case, it will render the view. Here, the color is white.

So, in this way, you can use ngSwitch in Angular 10.