What are the differences between [ngSwitch]
and a bunch of *ngIf
s. Any performance factors we should be concerned about?
*ngIf
<div *ngIf="day === 'MONDAY'">
Keep calm and pretend it's not Monday.
</div>
...
<div *ngIf="day === 'FRIDAY'">
Happy Friday!
</div>
[ngSwitch]
<ng-container [ngSwitch]="day">
<div *ngSwitchCase="'MONDAY'">
Keep calm and pretend it's not Monday.
</div>
...
<div *ngSwitchCase="'FRIDAY'">
Happy Friday!
</div>
</ng-container>
For *ngIf
, every condition will be checked and the code inside the true
condition will be executed.
For [ngSwitch]
, only the code inside the specific case will be executed (using break;
).
So, [ngSwitch]
will be faster where there are multiple cases.
ngIf is basically a version of ngSwitch with a single condition. It's different from ngShow in that it removes the actual DOM element rather than simply hiding it. If you're using an ngSwitch with just a singly truthy condition check, then I believe ngIf will do the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With