Consider this Angular template snippet:
<div [ngSwitch]="status"> <p *ngSwitchCase="'loading'">Loading...</p> <p *ngSwitchCase="'success'">Data loaded successfully!</p> <p *ngSwitchCase="'error'">Error occurred.</p> <p *ngSwitchDefault>Unknown status.</p> </div>
If the component's status property is set to 'success', what will be displayed?
Look at which *ngSwitchCase matches the status value.
The *ngSwitchCase directive renders the block whose value matches the status. Since status is 'success', the second paragraph is shown.
You want to display the same message for both 'pending' and 'in-progress' statuses using *ngSwitch. Which template snippet is correct?
Remember that *ngSwitchCase accepts one value per case.
You cannot combine multiple values in one *ngSwitchCase using logical operators or arrays. You must write separate cases for each value.
Given this Angular template and component code:
<div [ngSwitch]="user.role">
<div *ngSwitchCase="'admin'">
<span *ngSwitch="user.status">
<em *ngSwitchCase="'active'">Admin Active</em>
<em *ngSwitchCase="'inactive'">Admin Inactive</em>
<em *ngSwitchDefault>Admin Unknown</em>
</span>
</div>
<div *ngSwitchCase="'guest'">Guest User</div>
<div *ngSwitchDefault>Unknown Role</div>
</div>And the component has user = { role: 'admin', status: 'inactive' }. What will be displayed?
Check the outer *ngSwitchCase first, then the inner one.
The outer switch matches 'admin', so the inner switch checks user.status. Since status is 'inactive', it renders 'Admin Inactive'.
Examine this Angular template:
<div [ngSwitch]="color"> <p *ngSwitchCase="red">Red color</p> <p *ngSwitchCase="blue">Blue color</p> <p *ngSwitchDefault>Unknown color</p> </div>
If the component's color property is set to 'red' (string), why does it always show 'Unknown color'?
Check how string literals are written in Angular templates.
The *ngSwitchCase values must be string literals enclosed in quotes. Without quotes, Angular treats them as variables, which are undefined, so no case matches.
Consider an Angular template with multiple *ngSwitchCase directives that could match the same value due to overlapping expressions. What is Angular's behavior in this scenario?
Think about how switch statements work in programming languages.
Angular's *ngSwitch behaves like a traditional switch: it renders only the first matching case and skips the rest.