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:
[ngSwitch]="expression"is used on the parent element.- Child elements with
*ngSwitchCase="value"are placed inside for specific variants. - You can specify
*ngSwitchDefaultfor 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:
ngSwitchcontrols the selection of one of several elements in the DOM based on the value of an expression.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.