Loading
*ngSwitch directive-tutorial
The *ngSwitch directive is a structural directive in Angular. It helps you show or hide content based on the value of an expression, similar to how a switch statement works in programming.
You can think of it as
If this value matches case A, show block A. If it matches case B, show block B. Otherwise, show a default block.
It is very useful when you have multiple possible states or values, and you want to display different HTML for each.



Syntax:

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

  • expression - is what you check (for example, order status)
  • *ngSwitchCase - matches a value to show specific content
  • *ngSwitchDefault - shown if no cases match



Example: Using ngSwitch in Angular


Step 1: Create a New Angular Project

ng new ng-switch-example



Step 2: Generate  a New Component

ng g c status

This creates a component named StatusComponent.



Step 3: Add ngSwitch in the Template

Edit status.component.html

<div>
    <h2>Order Status</h2>
    <div [ngSwitch]="orderStatus">
        <p *ngSwitchCase="'placed'">✅ Order Placed</p>
        <p *ngSwitchCase="'dispatched'">🚚 Order Dispatched</p>
        <p *ngSwitchCase="'delivered'">📦 Order Delivered</p>
        <p *ngSwitchDefault>⌛ Order Pending</p>
    </div>
</div>

Here

  • orderStatus is the variable whose value we check.
  • Based on its value, Angular shows different messages.



Step 4: Define the order status in TypeScript

Edit status.component.ts

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 = 'placed'; // Change this value to test different cases

  constructor() {}

  ngOnInit() {}
}



Step 5: Use the Component in the App

Edit app.component.html to include your new status component

<app-status></app-status>



Step 6: Run the App

ng serve


Open your browser and go to: http://localhost:4200


You will see the message:

Order Placed

You can change orderStatus to 'dispatched' or 'delivered' in your TypeScript file to see different outputs.