Angular 2监视组件属性,用于在没有@Input或@Output的情况下进行的更改 [英] Angular 2 watch component property for changes without @Input or @Output

查看:66
本文介绍了Angular 2监视组件属性,用于在没有@Input或@Output的情况下进行的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 1.x中,我可以使用.$ watch观看我想要的任何内容,但是在Angular 2中,我们有ngOnChanges,它确实很酷,性能很好,但是只监视输入和输出装饰器.但是,我有时会确实需要监视本地属性,以便在它们更改时发出事件.我记得曾经看过一篇文章,该文章解释了如何显式告诉Angular 2观看单个属性,但是对我而言,我再也找不到该文章了,我所做的每一次搜索都告诉我将输入/输出装饰器与onChanges一起使用.如何为@ViewChild或其他本地属性创建观察者?

In Angular 1.x I could use .$watch to watch anything I wanted, however in Angular 2 we have ngOnChanges which is really cool and performant but only watches input and output decorators. However from time to time I really need to watch local properties so that I can emit an event when they change. I remember seeing an article explaining how you can explicitly tell Angular 2 to watch a single property but for the life of me I can't find the article anymore and every search I do just tells me to use the input/output decorators with onChanges. How can I create a watcher for a @ViewChild or other local properties?

例如,我有一个ngForm,当它的验证状态从有效更改为无效或反之时,我想将该状态发送给另一个组件,以便它可以做出反应.但是,由于我的ngForm是@ViewChild,而不是@Input或@Output,因此ngOnChanges无法检测到更改.

For example I have a ngForm, that when it's validation state changes from valid to invalid or vise versa I want to emit the state to another component so it can react. However since my ngForm is a @ViewChild and not a @Input or @Output ngOnChanges doesn't detect the change.

推荐答案

等效于Angular 2中的自定义Angular 1 $watch()是实现生命周期挂钩ngDoCheck()并执行您自己的检查. Lifecycle Hooks开发人员指南具有示例.

The equivalent to a custom Angular 1 $watch() in Angular 2 is to implement lifecycle hook ngDoCheck() and perform your own checking. The Lifecycle Hooks dev guide has an example.

请注意,每次运行更改检测(就像Angular 1手表一样)时,都会调用您的ngDoCheck()方法,因此请确保尽可能高效地实现该方法.

Note that your ngDoCheck() method will be called every time change detection runs (just like an Angular 1 watch), so be sure it is implemented as efficiently as possible.

如果可能的话,请尝试使用RxJS(可观察的,主题等),因为它更有效.我们曾经能够订阅NgForm的ControlGroup以便收到更改通知,但是我不知道那是不是仍然可用.

Try to use RxJS (an Observable, Subject, etc.) instead, if possible, as it is more efficient. We used to be able to subscribe to the NgForm's ControlGroup to be notified of changes, but I don't know if that is still available.

这篇关于Angular 2监视组件属性,用于在没有@Input或@Output的情况下进行的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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