I have a component with a few inputs that I'd like to be notified when it changes. I currently have it working by implementing ngOnChanges
and figuring out which input was changed. However, I would prefer set my input declaration to @Input('select-values') selectValues:Observable<any>
. This would allow me to subscribe to any new changes that occur in a much cleaner fashion.
ngOnInit() {
this.selectValues.subscribe(() => console.log('yay!'));
}
Issue with this is that I'm getting exception TypeError: this.selectValues.subscribe is not a function
.
Just found out that this also works – Component Interaction. Intercept input property changes with a setter.
In fact, it's not possible to directly register against observables associated with events for DOM elements. You need to reference a DOM element directly and use then the
fromEvent
method ofObservable
.Here is a sample:
This issue could interest you as well:
That said you can leverage form controls to be notified when input value is updated. The
valueChanges
attribute of the control could be passed as input of the sub component.You can wrap them in a form and listen to changes
http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/
or
See also this issue open https://github.com/angular/angular/issues/4062
If you just need to observe a single input, you can quickly do:
in component:
in html:
and maybe unsubscribe in ngOnDestroy.