【问题标题】:Angular2 - update bound property immediatelyAngular2 - 立即更新绑定属性
【发布时间】:2018-05-23 04:27:48
【问题描述】:

一开始我有一个简单的问题:“Angular2 中的绑定何时以及为什么要评估/更新?”

我想实现绑定属性在源设置后立即更新。

这个非常简单的 plunker 演示演示了该行为:

Plunker demo

还有代码中最有趣的部分:

setValue() {
   console.log(this.childComponent.prop);
   this.propValue = "button clicked";
   //NOW I WANT TO GET THE NEW VALUE
   console.log(this.childComponent.prop);
}

模板中更新后的插值表示绑定已正确评估并且目标属性已更新,但有时稍后会超出 setValue 方法范围。

为什么我想要这种行为?

我知道这种与组件交互的工作方式不是必需的,但是......我有一个更复杂的自定义表单控件(实现 ControlValueAccessor)。现在我正在研究一些“业务流程”:这个复杂组件的 ngModel 是更复杂对象的一部分,可以被更多组件访问,这些组件通常会影响彼此的对象部分。

简化示例:

型号

{
 public modelA: SomeClasss; <-- this is ngModel of comp. A
 public modelB: SomeClasss; {...} <-- this is ngModel of comp. B
}

同时在代码的其他地方:

update(X: SomeClass) {
    this.modelA = X;
    this.componentA.updateMagicUI();
}

updateMagicUI 方法带有一些复杂的逻辑,它根据新设置的值处理 ComponentA 的内部结构。请注意,当且仅当它被显式调用时,我才想执行此逻辑,而不是每次更改值时。

【问题讨论】:

    标签: angular data-binding binding


    【解决方案1】:

    this answer 中建议的一种触发变更检测的方法是调用ApplicationReftick 方法:

    import { ..., ApplicationRef } from '@angular/core'
    ...
    
    export class App {
      ...
      constructor(private applicationRef: ApplicationRef) {
        ...
      }
      setValue() {
        console.log(this.childComponent.prop);
        this.propValue = "button clicked";
        this.applicationRef.tick(); // Trigger change detection
        console.log(this.childComponent.prop);
      }
    }
    

    你可以在this plunker进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2016-09-23
      相关资源
      最近更新 更多