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

3

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>
Zymogenic answered 2/1, 2019 at 2:48 Comment(2)
codecraft.tv/courses/angular/built-in-directives/…Corpulence
similar using angular js - #16742449Rainier
S
11

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.

Sassan answered 2/1, 2019 at 4:14 Comment(0)
W
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.

Wolff answered 2/1, 2019 at 3:44 Comment(0)
C
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

Cannikin answered 2/1, 2019 at 4:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.