angular 6 variable or method binding in *ngIf
Asked Answered
A

3

5

Is there any difference between binding a variable and binding a method in template *ngIf.

Ex:

Case 1:

<div *ngIf="myVar">ABC</div>

Case 2:

<div *ngIf="myFunction()">ABC</div>

myFunction() : boolean {
   if (cond1 && cond2 && cond3) {
       return true;
   } else { 
       return false;
   }
}

Is there any impact on performance?

I am trying to use the 2 case, getting range Error: Maximum call stack exceeds.

Help me on this? Thanks

Aspia answered 7/8, 2018 at 9:20 Comment(4)
If you want to know how much trouble you might be in if you use a function - try adding console.count() inside of it, and see how many times it will be called.Arbalest
It is calling thousands of time.Aspia
That's exactly why you don't do that. Angular change detection will go through it again and again.Arbalest
If i want to do multiple condition checks like *ngIf="cond1 && cond2 && cond3 && con4". it will be very big line in the template i want to avoid that type of coding. Is there any way?Aspia
C
6

Yes there is

The first one wont have any performance issue since you are directly checking against a variable while the second one will have since angular uses change detection and it fires many times

Calan answered 7/8, 2018 at 9:23 Comment(0)
L
4

When u call a function angular fire the change detection cycle every time. better to use a get property

<div *ngIf="myvar">ABC</div>

get myvar() : boolean {
  if (cond1 && cond2 && cond3) {
    return true;
  } 
  return false;
}
Lixiviate answered 7/8, 2018 at 9:25 Comment(4)
In template i dont want to keep multiple condition checks, like <div *ngIf="cond1 && cond2 && cond3 && cond4">ABC</div>. So i started using method in *ngIf. That makes my code neat and clean.Aspia
What about in this case *ngIf="myFunction(arg1,arg2)" ?Aspia
then i would get the error getting range Error: Maximum call stack exceeds.Lixiviate
@SachilaRanawaka what makes you think that getters don't create the same performance issue?Adrenalin
P
0

what you can do to avoid performance issue is that you can make a class variable

public myVar = cond1 && cond2 && cond3

and then you can use it in first option and maintain readability of the code

Priority answered 7/8, 2018 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.