I have been fiddling around with reactive forms and valueChanges
subscription in Angular 2. I don;t quite get why certain form of subscribing seem not to be allowed.
this.form.get('name').valueChanges /* <- doesn't work */
.do(changes => {
console.log('name has changed:', changes)
});
.subscribe();
this.form.get('title').valueChanges.subscribe( /* <- does work */
changes => console.log('title has changed:', changes)
);
This plunker reproduces the problem (open DevTools console to see the error):
ZoneAwareError {stack: "Error: Uncaught (in promise): TypeError: Cannot se…g.com/[email protected]/dist/zone.js:349:25) []", message: "Uncaught (in promise): TypeError: Cannot set prope…ore.umd.js:8486:93)↵ at Array.forEach (native)", originalStack: "Error: Uncaught (in promise): TypeError: Cannot se…ps://unpkg.com/[email protected]/dist/zone.js:349:25)", zoneAwareStack: "Error: Uncaught (in promise): TypeError: Cannot se…g.com/[email protected]/dist/zone.js:349:25) []", name: "Error"…}
Is the first pattern (with do
) not illegal indeed?
FormControl The ValueChanges is an event raised by the Angular forms whenever the value of the FormControl, FormGroup or FormArray changes. It returns an observable so that you can subscribe to it. The observable gets the latest value of the control.
The ValueChanges is an event raised by the Angular forms whenever the value of the FormControl, FormGroup or FormArray changes. It returns an observable so that you can subscribe to it. The observable gets the latest value of the control.
An observable broadcasts a stream of information that can be read by any entity that is listening to the values the observable is outputting. Included with the many built-in observables in Angular 2 are observables to subscribe to form value changes.
As the form values change, this same object structure will be passed into the subscription with the updated form values. We get the sessionStorage object from the browser, and we associate the form values object to a key in the storage, in this case 'form'.
one of the way is:
debounceTime will make subscription after given milliseconds. If not required,ignore.
distinctUntilChanged will force subscription only on actual value change.
Update for Angular 8+
this.form.controls['form_control_name']
.valueChanges
.pipe(
.debounceTime(MilliSeconds)
.distinctUntilChanged()
)
.subscribe({
next: (value) => {
//use value here
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With