Angular 2形式+ OnPush [英] Angular 2 forms + OnPush

查看:66
本文介绍了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.

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

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(() => {});
    });
  }
}

但没有效果.

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

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天全站免登陆