*ngSwitch helps you show different parts of your page based on one value. It works like choosing from many options, so you only see what matches.
0
0
*ngSwitch for multiple conditions in Angular
Introduction
You want to show different messages based on a user's role like admin, guest, or member.
You need to display different icons depending on a status like loading, success, or error.
You want to switch between different layouts or sections based on a selected tab.
You want to show different content depending on a product type in a shopping app.
Syntax
Angular
<div [ngSwitch]="expression"> <div *ngSwitchCase="value1">Content for value1</div> <div *ngSwitchCase="value2">Content for value2</div> <div *ngSwitchDefault>Content if no cases match</div> </div>
The [ngSwitch] directive sets the value to check.
Each *ngSwitchCase shows content if it matches the value.
Examples
Shows a message based on the color variable's value.
Angular
<div [ngSwitch]="color"> <p *ngSwitchCase="'red'">Red color selected</p> <p *ngSwitchCase="'blue'">Blue color selected</p> <p *ngSwitchDefault>Other color</p> </div>
Displays different text depending on the user's role.
Angular
<div [ngSwitch]="userRole"> <span *ngSwitchCase="'admin'">Admin Panel</span> <span *ngSwitchCase="'guest'">Welcome Guest</span> <span *ngSwitchDefault>Unknown Role</span> </div>
Sample Program
This component shows a message based on the current status. Clicking the button cycles through different statuses to show how *ngSwitch changes the displayed message.
Angular
import { Component } from '@angular/core'; @Component({ selector: 'app-status-display', template: ` <h2>Status Checker</h2> <div [ngSwitch]="status"> <p *ngSwitchCase="'loading'">Loading... Please wait.</p> <p *ngSwitchCase="'success'">Success! Your data is ready.</p> <p *ngSwitchCase="'error'">Error occurred. Try again.</p> <p *ngSwitchDefault>Status unknown.</p> </div> <button (click)="changeStatus()">Change Status</button> ` }) export class StatusDisplayComponent { status = 'loading'; changeStatus() { const states = ['loading', 'success', 'error', 'unknown']; const currentIndex = states.indexOf(this.status); this.status = states[(currentIndex + 1) % states.length]; } }
OutputSuccess
Important Notes
Always include a *ngSwitchDefault to handle unexpected values.
*ngSwitch compares values strictly (===), so types must match exactly.
Summary
*ngSwitch helps show one of many options based on a value.
Use *ngSwitchCase for each choice and *ngSwitchDefault for fallback.
It keeps your templates clean and easy to read when handling multiple conditions.