13

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>
Manoj Shrestha
  • 4,246
  • 5
  • 47
  • 67

3 Answers3

10

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.

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
2

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.

0

*ngIf works like if statement and ngSwitch (actually comprised of two directives, an attribute directive, and a structural directive) work as a switch statement in the DOM.

Knowing the difference between if-else statement and switch cases will help you understand further, https://techdifferences.com/difference-between-if-else-and-switch.html

Akshay Rajput
  • 1,978
  • 1
  • 12
  • 22