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:

export class AppComponent {
  ...
  showTasksOf = "Developer";
  ...
}

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

<ul [ngSwitch]="showTasksOf">
  <li *ngSwitchCase="'Tester'">
    <ul>
      <li>Report Bugs</li>
      <li>Reopen Bugs</li>
      <li>Chill!!</li>
    </ul>
  </li>
  <li *ngSwitchCase="'Developer'">
    <ul>
      <li>Code Code Code</li>
      <li>Bingo</li>
      <li>Find Coffee!</li>
    </ul>
  </li>
  <li *ngSwitchCase="'Architect'">
    <ul>
      <li>Do crazy stuff</li>
      <li>Cloud mess</li>
      <li>Stroll!</li>
    </ul>
  </li>
  <li *ngSwitchCase="'Designer'">
    <ul>
      <li>Out of world</li>
      <li>Really??</li>
      <li>Draw anything</li>
    </ul>
  </li>

  <li *ngSwitchDefault>
    <ul>
      <li>Why you are here???</li>
    </ul>
  </li>
</ul>

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:

<ul [ngSwitch]="showTasksOf">
  <li *ngSwitchCase="'Developer'">
    <ul>
      <li>Code Code Code</li>
      <li>Bingo</li>
      <li>Find Coffee!</li>
    </ul>
  </li>
</ul>

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.

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments