Angular 2 表单 + OnPush [英] Angular 2 forms + OnPush

查看:17
本文介绍了Angular 2 表单 + OnPush的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 angular 2 应用程序,出于性能原因,我尝试在任何地方使用 ChangeDetectionStrategy.OnPush.我有一个需要 OnPush 才能顺利工作的复杂组件,其中包含另一个显示表单的组件(使用 FormBuilder 创建).我现在注意到当我点击一个滑块时,它的内部值会更新(即 form.value),但滑块组件并没有可视化这个新值,即它卡在旧位置.

I am writing an angular 2 application where I try to use ChangeDetectionStrategy.OnPush everywhere, for performance reasons. I have a complex component that needs OnPush in order to work smoothly, which contains another component that is displaying a form (created with FormBuilder). I now noticed that when I click on a slider, the internal value of it is updated (i.e. form.value), but the slider component does not visualize this new value, i.e. it is stuck at the old position.

我解决这个问题的第一个想法是将叶组件的更改检测策略设置为默认值,但这没有效果,因为显然这也需要更改其父组件的更改检测策略(这在我的应用程序中是不可能的).

My first idea to fix this, was to set the leaf component's change detection strategy to DEFAULT, but this had no effect as apparently this requires changing the change detection strategy of its parent components too (which is not possible in my application).

然后我想出了这个主意:

Then I came up with this idea:

@Component({
   ...
})
class MyComponent implements OnInit {
  constructor(private zone: NgZone) {}

ngOnInit() {
  INIT_FORM();

  this.form.valueChanges
    .subscribe(() => {
      this.zone.run(() => {});
    });
  }
}

但是没有效果.

是否有可能使 angular 2 表单在使用 OnPush 的组件内工作?

Is there any possibility to make angular 2 forms work inside a component that uses OnPush?

推荐答案

我自己没有测试,但手动调用变更检测可能会做你想做的:

Not tested myself but invoking change detection manually might do what you want:

@Component({
   ...
})
class MyComponent implements OnInit {
  constructor(private cdRef: ChangeDetectorRef) {}

ngOnInit() {
  INIT_FORM();

  this.form.valueChanges
    .subscribe(() => {
      this.cdRef.detectChanges();
    });
  }
}

这篇关于Angular 2 表单 + OnPush的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆