Ionic ngSwitch with examples

In Ionic Angular has a lot of built-in directives: *ngIf , *ngFor , *ngSwitch . These directives are so-called structural directives, which are used to transform the DOM structure.  Sometimes you need to render different elements depending on a given condition. When you run into this situation, you could solve this by using several *ngIf directives but it is better to use the ionic ngSwitch directive in such a situation.

In this article, we will learn how to use the ngSwitch directive in the Ionic Angular application. We have also demonstrated of Ionic ngSwitch example. Let get started.

Syntax of ionic ngSwitch directive of Angular

The ngSwitch directive selects one of several elements based on the expression result, similar to a JavaScript switch statement. This directive is for adding or removing DOM elements when they match switch expressions. The element that the ngSwitch directive is applied to is always included in the HTML document, and the directive name isn’t prefixed with an asterisk. It must be specified within square brackets, like this:

<container-element [ngSwitch]="switch_expression">
   <some-element *ngSwitchCase="match_expression_1">...</some-element>
     ...
   <some-element *ngSwitchDefault>...</some-element>
</container-element>
  1. ngSwitch: is a structural directive holding all expression bodies.
  2. *ngSwitchCase: have an expression for each matching condition and will render the corresponding template if its condition matches that of the ngSwitch have.
  3. *ngSwitchDefault: element is optional and it will render when any of the match condition is failed.

An Ionic ngSwitch example in ionic angular

To check how NgSwitch operates, we have an example below and set a variable page to about in the typescript component. The ngSwitch expression will check the matching the expression of each ngSwitchCase, will render the corresponding paragraph in about when matched is found.

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

@Component({
  selector: 'app-home',
  template:
    `
    <ul class="nav">
  <li [class.active]="page=='page'">
    <a (click)="page='info'">Info</a></li>
    <li [class.active]="page=='about'">
      <a (click)="page='about'">About</a>
    </li>
    <li [class.active]="page=='Contact'">
      <a (click)="page='contact'">Contact</a>
    </li>
</ul>
<div [ngSwitch]="page">
      <p *ngSwitchCase="'info'">Information Page</p>
      <p *ngSwitchCase="'about'">About Page </p>
      <p *ngSwitchCase="'contact'">Contact page</p>
      <p *ngSwitchDefault>Home</p>
</div>
    `,
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  page = 'about';
}
ionic ngSwitch example

Conclusion
In this article, we have explored details on Angular directives ngSwitch directive. We demonstrate an example also and I hope you got an idea of how to use it.

Related posts

Spread the love

Leave a Comment

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

Scroll to Top