Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 watch component property for changes without @Input or @Output

Tags:

angular

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?

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.

like image 828
efarley Avatar asked Aug 23 '16 21:08

efarley


1 Answers

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.

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.

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.

like image 175
Mark Rajcok Avatar answered Nov 14 '22 00:11

Mark Rajcok