Skip to main content

What does the ngSwitch directive do?

The ngSwitch directive in Angular is a structural directive that lets you display one of several element variants depending on the value of an expression.

How it works:

  1. [ngSwitch]="expression" is used on the parent element.
  2. Child elements with *ngSwitchCase="value" are placed inside for specific variants.
  3. You can specify *ngSwitchDefault for the case when no case matches.

Example:

html
<div [ngSwitch]="color"> <p *ngSwitchCase="'red'">Red is selected</p> <p *ngSwitchCase="'blue'">Blue is selected</p> <p *ngSwitchDefault>No color selected</p> </div>

If color = 'blue', Angular renders only <p>Blue is selected</p>.

Conclusion: ngSwitch controls the selection of one of several elements in the DOM based on the value of an expression.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.