How to Use ngSwitch in Angular: Simple Guide with Examples
Use
ngSwitch on a container element to switch views based on a value, and inside it use *ngSwitchCase for matching cases and *ngSwitchDefault for the fallback. Angular shows only the matching case's content, hiding others automatically.Syntax
The ngSwitch directive is placed on a container element to watch a value. Inside it, use *ngSwitchCase to define blocks that show when the value matches, and *ngSwitchDefault for a fallback when no cases match.
Example parts:
[ngSwitch]="expression": The value to check.*ngSwitchCase="value": Content shown if expression equals this value.*ngSwitchDefault: Content shown if no cases match.
html
<div [ngSwitch]="color"> <p *ngSwitchCase="'red'">Red color selected</p> <p *ngSwitchCase="'blue'">Blue color selected</p> <p *ngSwitchDefault>Unknown color</p> </div>
Example
This example shows how to use ngSwitch to display different messages based on a selected color variable in the component.
typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-color-switch', template: ` <h3>Select a color:</h3> <button (click)="color = 'red'">Red</button> <button (click)="color = 'blue'">Blue</button> <button (click)="color = 'green'">Green</button> <div [ngSwitch]="color" style="margin-top: 20px; font-weight: bold;"> <p *ngSwitchCase="'red'">You picked Red!</p> <p *ngSwitchCase="'blue'">You picked Blue!</p> <p *ngSwitchDefault>Color not recognized.</p> </div> ` }) export class ColorSwitchComponent { color = ''; }
Output
Buttons labeled Red, Blue, Green appear. Clicking a button shows a message below: 'You picked Red!' or 'You picked Blue!' or 'Color not recognized.' for Green.
Common Pitfalls
Common mistakes when using ngSwitch include:
- Forgetting the square brackets on
[ngSwitch], which binds the expression. - Using
ngSwitchCasewithout the asterisk*, which is required for structural directives. - Not providing a
*ngSwitchDefault, which can leave the UI blank if no cases match. - Using non-strict equality checks by mistake;
ngSwitchCaseuses strict equality (===).
Example of wrong and right usage:
html
<!-- Wrong: missing brackets and asterisk --> <div ngSwitch="color"> <p ngSwitchCase="'red'">Red</p> </div> <!-- Right: correct binding and structural directives --> <div [ngSwitch]="color"> <p *ngSwitchCase="'red'">Red</p> </div>
Quick Reference
| Directive | Purpose |
|---|---|
| [ngSwitch] | Binds the value to switch on |
| *ngSwitchCase | Displays content if value matches case |
| *ngSwitchDefault | Displays content if no cases match |
Key Takeaways
Use [ngSwitch] on a container to watch a value and *ngSwitchCase for matching cases.
Always include *ngSwitchDefault to handle unmatched cases gracefully.
Use the asterisk (*) before ngSwitchCase and ngSwitchDefault as they are structural directives.
ngSwitchCase uses strict equality (===) to compare values.
Remember to bind [ngSwitch] with square brackets for dynamic evaluation.