简体   繁体   English

* ngIf中的角度6变量或方法绑定

[英]angular 6 variable or method binding in *ngIf

Is there any difference between binding a variable and binding a method in template *ngIf. 绑定变量和绑定模板* ngIf中的方法之间是否有任何区别。

Ex: 例如:

Case 1: 情况1:

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

Case 2: 案例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. 我正在尝试使用2种情况,获取范围错误:最大调用堆栈超出。

Help me on this? 帮我这个? Thanks 谢谢

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 第一个没有任何性能问题,因为你直接检查一个变量,而第二个将有角度使用变化检测,它会多次触发

When u call a function angular fire the change detection cycle every time. 当你每次调用一个函数角火时都会改变检测周期。 better to use a get property 最好使用get属性

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

get myvar() : boolean {
  if (cond1 && cond2 && cond3) {
    return true;
  } 
  return false;
}

what you can do to avoid performance issue is that you can make a class variable 你可以做些什么来避免性能问题是你可以创建一个类变量

public myVar = cond1 && cond2 && cond3 public myVar = cond1 && cond2 && cond3

and then you can use it in first option and maintain readability of the code 然后你可以在第一个选项中使用它并保持代码的可读性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM