My Reactive Angular Form should be submitted on Key Up if the form is valid.
I registerd a subscriber on valueChanges
but it is called onKeyUp and onBlur of each input and the form is submitted twice. It seems that this is a known issue (https://github.com/angular/angular/issues/12540) and as a solution distinctUntilChanged
is suggested.
Unfortunately is seems not to work in my case. The submit is fired immediately no matter what time I set and still fired twice.
this.myFormGroup.valueChanges
.pipe(debounceTime(2000), distinctUntilChanged())
.subscribe(() => {
if (this.myFormGroup.valid) {
this.submitForm();
}
});
Does someone have an idea what could be my mistake with distinctUntilChanged
? Or is there another method to prevent valueChanges
to be fired onKeyUp and onBlur?
distinctUntilChanged uses ===
comparison by default, object references must match , myFormGroup
will emit an object in every change and these objects are not the same reference
try to add custom method to handle changes
distinctUntilChanged((p: any, n: any) => JSON.stringify(p) === JSON.stringify(n))