angulartypescriptangular-reactive-formsangular2-form-validation

Angular Reactive Forms - Perform Validation After Form Fields Shown / Hidden on Value Changes


I'm working with reactive forms with various required fields to validate. Certain fields have conditional validation that should only be checked if the conditions are met. (i.e. If you answered yes to the above question, please explain why)

In HTML that ends up looking like this:

<input type="text" [required]="did_you_answer_yes_to_the_previous_question" />

That way, the reactive form doesn't validate that field unless the conditions are met.

I then check the form validity on valueChanges like so:

    this.form.valueChanges
        .pipe(
            concatMap((updatedForm: any) => {
                if (this.form.dirty) {                      
                    this.service.udpateFormIsValid(this.form.valid);
                    this.form.markAsPristine();
                }

                return of(updatedForm);
            })
        )
        .subscribe((updatedForm: any) => {  });

However, the validation occurs before the angular bindings update causing false positives and negatives.

I can easily fix it by adding a .debounceTime(250) after the valueChanges observable to alleviate the race condition, but adding a manual delay seems like an anti-pattern.

Are there any better ways to ensure we perform the check every time the form updates but do it after angular has updated the boolean conditional bindings?


Solution

  • FormControl has a statusChanges Observable you can subscribe to.

    So the code could look something like this:

            this.form.statusChanges
                .pipe(
                    distinctUntilChanged()) // to reduce the noise
                .subscribe(() => {
                    this.service.udpateFormIsValid(this.form.valid);
            });