AppDividend
Latest Code Tutorials

Angular NgSwitch Example | ngswitch Directive In Angular

0

Angular NgSwitch structural directive that adds or removes templates (displaying or hiding views) when the next match expression matches the switch expression. The NgSwitch directive lets you hide/show HTML elements depending on a feeling.

Angular NgSwitch

Angular NgSwitch directive is used to conditionally swap the DOM structure on your template based on a scope expression. Elements within NgSwitch but without NgSwitchDefault directives will be preserved at the location as specified in the template.

NgSwitch chooses one of the nested elements and makes it visible based on which item matches the value obtained from the evaluated expression.

In other words, you define the container element (where you place the directive), place the expression on the on=”…” attribute (or the NgSwitch=”…” attribute), define any inner items inside of the directive and place a when attribute per item.

When the attribute is used to inform NgSwitch, which item to display when the on expression is evaluated if the matching expression is not found via the when attribute, then an item with the default attribute is displayed.

The [ngSwitch] directive on the container specifies an expression to match against.

The expressions to match are provided by the ngSwitchCase directives on views within the container.

  1. Every view that matches are rendered.
  2. If there are no matches, the view with a ngSwitchDefault directive is rendered.
  3. Elements within the [NgSwitch] statement but outside of any NgSwitchCase or ngSwitchDefault directive are preserved at the location.

Define the container element for the directive and specify a switch expression to match against as an attribute.

<container-element [ngSwitch]="switch_expression">

Within the container, *ngSwitchCase statements specify the match expressions as attributes.

Include *ngSwitchDefault as a final case.

<container-element [ngSwitch]="switch_expression">
   <some-element *ngSwitchCase="match_expression_1">...</some-element>
...
   <some-element *ngSwitchDefault>...</some-element>
</container-element>

Selector

[ngSwitch]

Properties

Property Description
@Input()
ngSwitch: any
Write-Only

NgSwitch Example

Let’s imagine we wanted to print shows names in different colors depending on where they are on streaming right now.

With a bootstrap framework, we can change the text color by using the text-danger, text-success, text-warning, and text-primary classes.

We could solve this by having the series of *ngIf statements, like so,

<ul *ngFor="let show of shows">
  <li *ngIf="show.service ==='Netflix'"
      class="text-success">{{ show.name }} ({{ show.name }})
  </li>
  <li *ngIf="show.service === 'Disneyplus'"
      class="text-primary">{{ show.name }} ({{ show.name }})
  </li>
  <li *ngIf="show.service === 'HBOMax'"
      class="text-danger">{{ show.name }} ({{ show.country }})
  </li>
  <li *ngIf="show.service !== 'HBOMax' && person.country !== 'Netflix' && person.country !== 'Disneyplus'"
      class="text-warning">{{ show.name }} ({{ show.country }})
  </li>
</ul>

This initially seems to make sense until we try to create the else style item.

We have to check to see if the show is not from any of the services we have specified before.

Resulting in a pretty long ngIf expression, and it will only get worse the more when we add new services.

Most languages, including the javascript or typescript, have the language construct called the switch statement to solve this kind of problem.

Angular also provides us with the same functionality via something called the NgSwitch directive.

This directive allows us to render different items depending on the given condition, and in fact, the NgSwitch directive is several directives working in conjunction.

Okay, let’s deep dive into the example.

Step 1: Install the Angular project

Type the following command.

ng new angular-ngswitch

When you install a brand new Angular project, see the options they are providing while creating a new project. In this project, we need the routing module, so we will allow the Angular CLI to generate a routing module for us.

I am using Visual Studio Code as a programming editor to develop Angular application.

Now, go inside the folder and open the project inside the VSCode.

Step 2: Write demo data in an app.component.ts file

Write the following code inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  shows: any[] = [
    {
      name: 'Stranger Things',
      service: 'Netflix',
    },
    {
      name: 'The Mandalorian',
      service: 'Disneyplus',
    },
    {
      name: 'Game of Thrones',
      service: 'HBOMax',
    },
    {
      name: 'Amazon Prime',
      service: 'Fleabag',
    }
  ];
}

In the above code, we have added an array of objects so that we can use that in an angular switch statement.

Step 3: Write a view app.component.html file.

Now, in this file, we include the NgSwitch directive.

<div class="container">
  <h4>NgSwitch Example</h4>
  <ul *ngFor="let show of shows" [ngSwitch]="show.service">
    <li *ngSwitchCase="'Netflix'" class="text-success">{{ show.name }} ({{ show.service }})
    </li>
    <li *ngSwitchCase="'Disneyplus'" class="text-primary">{{ show.name }} ({{ show.service }})
    </li>
    <li *ngSwitchCase="'HBOMax'" class="text-danger">{{ show.name }} ({{ show.service }})
    </li>
    <li *ngSwitchDefault class="text-warning">{{ show.name }} ({{ show.service }})
    </li>
  </ul>
</div>

We bind the expression to a ngSwitch directive.

Angular ngSwitchCase directive lets us define a condition which if it matches the expression, then it will render the item it’s attached to.

If no conditions are met in the switch statement it will check to see if there is a NgSwitchDefault directive, if there is it will render the element that’s attached to, however, it is optional and if it’s not present, it won’t display anything if no matching ngSwitchCase directive is found.

The main difference between the ngIf solution is that by using Angular NgSwitch, we evaluate an expression only once and then choose the element to display based on the result.

Let’s see the following output.

 

ngswitch Directive In Angular

The use of the NgSwitch case is in the above example is just, an example, and isn’t an efficient way of solving this problem. This is just a demo and practical example of how we can use it inside our regular project.

We would use either the NgStyle or NgClass directives for the above example.

With the use of NgIf, we can conditionally add or remove an element from the DOM.

If we are faced with multiple conditions, a cleaner alternative to multiple nested NgIf statements is the NgSwitch series of directives.

Let’s remove some of the properties of the shows object.

Write the following code inside the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  shows: any[] = [
    {
      name: 'The Mandalorian',
      service: 'Disneyplus',
    }
  ];
}

Now, we have only one property of Mandalorian, and now we should see only one show on the screen. Save the file, and you will see only Mandalorian will appear on the screen.

That means only this property matches in the switch expression and prints on the screen.

Finally, Angular NgSwitch Example | ngswitch Directive In Angular Tutorial is over.

Related Posts

Angular CRUD Operations

Angular Forms Tutorial

Angular HttpClient Example

Angular Routing Example

How To Update Angular CLI

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.