What design pattern can be applied to angular component where form changes are debounced to avoid losing change events

Viewed 45

I am experiencing a frustrating issue with an Angular 14 application that I can only assume is caused by some fundamental design flaw to cause complications.

Imagine the app allows the user to navigate between questions in a questionnaire and each page has a form that allows the user to input data against it. The input fields of type text are debounced using the following code: -

        this._formGroupChangedSubscription = this.formGroup.valueChanges
            .pipe(debounceTime(400), distinctUntilChanged())
            .subscribe(() => {
                this.onValueChanges();
            });

This works fine until you try to be devilish with your input and enter some text into the input box and then very quickly click next to move to the next question. The data capture component is different depending on the question type thus the first component is destroyed and the subscription subsequently destroyed before it gets an opportunity to be executed.

1 Answers

If the component destruction is the issue, move your subscription to a service or emit this.formGroup immediately onDestroy hook.

ngOnDestory(): void {
   this.onValueChanges();
}
Related