【问题标题】:angular 6 variable or method binding in *ngIf*ngIf 中的 Angular 6 变量或方法绑定
【发布时间】:2018-08-07 09:20:38
【问题描述】:

在模板*ngIf中绑定变量和绑定方法有什么区别。

例如:

案例 1:

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

案例 2:

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

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

对性能有影响吗?

我正在尝试使用第 2 种情况,获取范围错误:超过最大调用堆栈。

帮我解决这个问题?谢谢

【问题讨论】:

  • 如果你想知道如果你使用一个函数会遇到多少麻烦 - 尝试在其中添加console.count(),看看它会被调用多少次。
  • 千呼万唤。
  • 这正是你不这样做的原因。角度变化检测会一次又一次地进行。
  • 如果我想做多个条件检查,比如 *ngIf="cond1 && cond2 && cond3 && con4"。这将是模板中非常大的一行,我想避免这种类型的编码。有什么办法吗?

标签: angular variable-binding


【解决方案1】:

第一个不会有任何性能问题,因为您是直接检查变量,而第二个将有,因为 angular 使用更改检测并且它会触发多次

【讨论】:

    【解决方案2】:

    当你调用一个函数时,每次都会触发变化检测周期。最好使用 get 属性

    <div *ngIf="myvar">ABC</div>
    
    get myvar() : boolean {
      if (cond1 && cond2 && cond3) {
        return true;
      } 
      return false;
    }
    

    【讨论】:

    • 在模板中我不想保留多个条件检查,例如
      ABC
      。所以我开始在 *ngIf 中使用方法。这使我的代码整洁干净。
    • 在这种情况下怎么办 *ngIf="myFunction(arg1,arg2)" ?
    • 然后我会收到错误getting range Error: Maximum call stack exceeds.
    【解决方案3】:

    为了避免性能问题,你可以做一个类变量

    public myVar = cond1 && cond2 && cond3

    然后您可以在第一个选项中使用它并保持代码的可读性

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 2020-09-28
      • 2017-06-03
      • 2019-05-08
      • 2020-06-21
      • 1970-01-01
      • 2019-03-01
      • 2019-09-18
      • 2019-05-02
      相关资源
      最近更新 更多