Loading

Quipoin Menu

Learn • Practice • Grow

angular / ngSwitch Directive
tutorial

ngSwitch Directive

Imagine a traffic light. It shows either red, yellow, or green – never more than one at a time. Angular's *ngSwitch directive works the same way – it displays one element from a set of choices based on a condition.

The *ngSwitch directive is actually a set of three directives that work together:

  • ngSwitch – The container directive that evaluates the expression.
  • *ngSwitchCase – Renders its element when the value matches.
  • *ngSwitchDefault – Renders when no case matches.

Here's an example:


@Component({
selector: 'app-user-role',
template: `
<div [ngSwitch]="userRole">
<p *ngSwitchCase="'admin'">Welcome, Administrator! You have full access.</p>
<p *ngSwitchCase="'editor'">Welcome, Editor! You can edit content.</p>
<p *ngSwitchCase="'viewer'">Welcome, Viewer! You can only view content.</p>
<p *ngSwitchDefault>Welcome, Guest! Please log in.</p>
</div>

<button (click)="changeRole('admin')">Admin</button>
<button (click)="changeRole('editor')">Editor</button>
<button (click)="changeRole('viewer')">Viewer</button>
<button (click)="changeRole('guest')">Guest</button>
`

})
export class UserRoleComponent {
userRole = 'guest';

changeRole(role: string) {
this.userRole = role;
}
}

Another example with multiple elements per case:


<div [ngSwitch]="status">
<div *ngSwitchCase="'loading'>
<div class=""spinner""></div>
<p>Loading data...</p>
</div>

<div *ngSwitchCase=""'success'">
<div class=""success-icon"">✓</div>
<p>Data loaded successfully!</p>
</div>

<div *ngSwitchCase=""'error'">
<div class=""error-icon"">✗</div>
<p>Failed to load data. Please try again.</p>
</div>

<div *ngSwitchDefault>
<p>Ready to load data.</p>
</div>
</div>
Two Minute Drill
  • ngSwitch shows one element from multiple choices.
  • Use [ngSwitch] on a container element.
  • Use *ngSwitchCase for each matching value.
  • Use *ngSwitchDefault for fallback.
  • Perfect for role-based UI status messages multi-step forms.
"

Need more clarification?

Drop us an email at career@quipoinfotech.com