Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 6 variable or method binding in *ngIf

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

like image 436
Yashavanta Byagawadi Avatar asked Jan 03 '23 01:01

Yashavanta Byagawadi


2 Answers

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

like image 54
Sajeetharan Avatar answered Jan 16 '23 12:01

Sajeetharan


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;
}
like image 30
Sachila Ranawaka Avatar answered Jan 16 '23 13:01

Sachila Ranawaka