Performance: *ngSwitch for multiple conditions
This affects rendering speed and visual stability by controlling which elements are added or removed from the DOM based on multiple conditions.
<div [ngSwitch]="condition"> <div *ngSwitchCase="'condition1'">Block 1</div> <div *ngSwitchCase="'condition2'">Block 2</div> <div *ngSwitchCase="'condition3'">Block 3</div> <div *ngSwitchDefault>Default Block</div> </div>
<div *ngIf="condition1">Block 1</div> <div *ngIf="condition2">Block 2</div> <div *ngIf="condition3">Block 3</div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple *ngIf for each condition | Multiple nodes created/destroyed independently | Multiple reflows per condition change | Higher paint cost due to layout shifts | [X] Bad |
| Single *ngSwitch with cases | Only one node subtree created/destroyed | Single reflow per switch change | Lower paint cost with stable layout | [OK] Good |
*ngSwitch?*ngSwitch*ngSwitch is used to conditionally display one of many templates based on a value.*ngSwitch chooses one template to show from multiple options.*ngSwitchCase inside an *ngSwitch block?*directiveName="expression" syntax for structural directives.*ngSwitchCase*ngSwitchCase="value", with quotes around the value.<div [ngSwitch]="color"> <div *ngSwitchCase="'red'">Stop</div> <div *ngSwitchCase="'green'">Go</div> <div *ngSwitchCase="'yellow'">Wait</div> <div *ngSwitchDefault>Unknown</div> </div>
color = 'yellow'?colorcolor is set to 'yellow'.color with *ngSwitchCase values*ngSwitchCase="'yellow'" matches the value.<div [ngSwitch]="status"> <div *ngSwitchCase=active>Active</div> <div *ngSwitchCase="inactive">Inactive</div> <div *ngSwitchDefault>Unknown</div> </div>
*ngSwitchCase values*ngSwitchCase=active without quotes, which is invalid for string values.*ngSwitchCase="'active'" or *ngSwitchCase="active" if active is a variable.*ngSwitch to handle this?[ngSwitch] binding[ngSwitch]="userRole".*ngSwitchCase values are strings with quotes*ngSwitchCase="'admin'".*ngSwitchDefault without a value, which is correct.Pass the test and this pattern moves unknown