Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different between *ngIf vs [ngSwitch] in Angular 2+

What are the differences between [ngSwitch] and a bunch of *ngIfs. 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>
like image 395
Manoj Shrestha Avatar asked Jan 02 '19 02:01

Manoj Shrestha


2 Answers

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.

like image 98
Yasir Arafat Avatar answered Sep 28 '22 09:09

Yasir Arafat


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.

like image 39
Gourav Singla Avatar answered Sep 28 '22 08:09

Gourav Singla