Angular Built-in Directives: ngSwitch

On the last tutorial article, we discussed ngIf. In this post, we will go through another Angular built-in directive called ngSwitch.

ngSwitch basically adds or removes a DOM element whenever it has a match to specific switch case expression. In case of not having a match on all of the cases, a default switch case should also be provided.


Let’s do an example. Our goal here is to show the corresponding meaning of the abbreviated stock markets.


Now looking at it in code, go back to stocks.component.ts file.

  • This ngSwitch statement is using the string ‘NYSE’ as the condition for the switch cases.
  • The condition is equivalent to the first switch case so it will show ‘New York Stock Exchange’.
  • If you change the condition to ‘LSE’, the output would be the London Stock Exchange.

But of course, ngSwitch can be modified to have more control of the conditional statement. Let’s say we’ll use a variable as the switch case. Create a variable named ‘market’ and use it in our switch statement.

This will work just the same as the hard coded one but this way, it adds more flexibility for your app. You may freely add or subtract switch cases as you wish but make sure a default case is always present in your statement. That’s it for Angular ngSwitch.

Next in the series of built-in directives is ngStyle.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.