Angular 8/7 | NgSwitch quick tutorial by example

Applying conditional expressions to add or remove elements in Document Object Model (DOM) i.e our HTML structure we usually use NgIf, NgIf ELse or NgIf Then Else. But if there are more then two outputs other then true or false, NgIf simply makes conditional expressions more complex and messy.

Switch case strategy which we use in JavaScript is available in Angular as NgSwitch Directive. NgSwitch Directive can be used to match multiple conditions while keeping the DOM structure simple, clean and easy to understand.

Let’s check a quick example first for quick visitors 🙂

In Component class we have:

Here we defined showTaskOf with “Developer” then in HTML template we use NgSwtich as follows:

In the above code we have three Directives:

[ngSwitch]: This will have value(s) which will be matched to any of *ngSwitchCase

*ngSwitchCase: The value assigned to this is matched show or remove an element from DOM.

*ngSwitchDefault: If none of the value is matched then Default sections appears acts like else block.

In our above block as we assigned “Developer” to [ngSwitch], so following DOM structure will remain in the view:

That’s it! Simple Right?

Here we discussed how we can easily implement NgSwitch case in angular application to match multiple expressions in DOM structure.

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of