Loading

*ngSwitch directive

  • The ngSwitch directive in Angular is a structural directive that facilitates the rendering of content based on a specified condition. 
  • It's akin to a switch statement in traditional programming languages and is used to display different sections of content based on different values or cases

Syntax:

<div [ngSwitch]="expression">
  <div *ngSwitchCase="value1">Content for value1</div>
  <div *ngSwitchCase="value2">Content for value2</div>
  <div *ngSwitchDefault>Default content</div>
</div>

Example:

Step 1: Create an Angular project using Angular CLI.

ng new ng-switch-example

Step 2: Create a new component message

ng g c status

Step 3: Edit the 'status.component.html' to use '*ngSwitch' :

<div>
  <h2>Order Status</h2>
  <div [ngSwitch]="orderStatus">
    <p *ngSwitchCase="'value1'">Order Placed</p>
    <p *ngSwitchCase="'value2'">Order Dispatched</p>
    <p *ngSwitchCase="'value3'">Order Delivered</p>
    <p *ngSwitchDefault>Order Pending</p>
  </div>
</div>

Step 4: Edit the 'status.component.ts' to define the component's logic.

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


@Component({
  selector: 'app-status',
  templateUrl: './status.component.html',
  styleUrls: ['./status.component.css']
})
export class StatusComponent implements OnInit {

  orderStatus: string = 'value 1';
  constructor() { }

  ngOnInit() {
  }

}

Step 5: Add the ‘<app-status></app-status>’ to the ‘app.component.html’ to include the ‘status component’ in the main application.

<app-status></app-status>

Step 6: Now run or compile the application.

ng serve

You will see the result on http://localhost:4200