Angular ngSwitch Directive

In the previous article, we’ve learned about the ngIf directive. In this article, we are going to learn about the ngSwitch directive and its working.

What is the Angular ngSwitch Directive?

The ngSwitch is basically a built-in template directive used to display HTML elements into the View after the evaluation switch statement. It’s the same as a switch case in any programming language. Of course, we know that HTML is not a programming language, but analogically, this makes HTML a programming language and makes developer’s work easy.

Let’s see the syntax to understand it:

<div [ngSwitch]="color">
  <h1 *ngSwitchCase="'violet'">You Selected Violet </h1>
  <h1 *ngSwitchCase="'green'">You Selected Green </h1>
  <h1 *ngSwitchCase="'blue'">You Selected Blue </h1>
</div>
  • The ngSwitch is attached with a color
  • Now in the h1 tag, we specified the switch cases with *ngSwitchCase.
  • In the first case, we’re checking if the color is violet, similar in the second and third with green and blue.
  • Color is the property that we created in that file.
  • Color is assigned with a string value

Example

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  color="blue"
}

Output:

angular ngSwitch directive example

Here the You Selected Blue is displayed into the view only because we assigned color property with blue.

Conclusion

We hope this article has helped clear your concepts on the ngSwitch directive, and it’s working. It was pretty easy and similar to the other ones. In the next article, we’ll learn about the more important topic of Angular, i.e., Pipes. After that, we’ll move on to some other important topics of Angular.

Read Next: Angular Pipes

Leave a Reply

Your email address will not be published. Required fields are marked *