Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular 4, why do asynchronously validated nested controls not propagate their validity to the parent FormGroup?

In my Angular 4.0.2 app, I have a FormGroup containing a nested component that implements ControlValueAccessor and Validator. This component validates itself asynchronously. The problem is, even when the nested component becomes valid, the parent FormGroup remains invalid.

But, if I simply change the validation to be synchronous, the validity propagates correctly to the parent group.

I have boiled it down as minimally as possible to the following Plunker:

http://plnkr.co/edit/H26pqEE3sRkzKmmhrBgm

Here is a second Plunker showing a similar setup, but this time the input FormControl is directly inside the FormGroup rather than being part of a nested component. Here, asynchronous validation propagates correctly:

http://plnkr.co/edit/DSt4ltoO1Cw2Nx1oXxbD

Why is my asynchronous validator not propagating its validity when defined inside a component?


Here is the code from the first (broken) Plunker:

import {Component, NgModule, VERSION, forwardRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FormsModule, ReactiveFormsModule} from '@angular/forms'
import {Observable} from 'rxjs/Rx'
import {
    FormGroup, FormControl, FormBuilder, Validators, AbstractControl, Validator,
    ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, ValidationErrors
} from '@angular/forms';


@Component({
  selector: 'my-app',
  template: `
<p>When validated asyncronously, why is the parent form group invalid even though its 
inner control is valid?</p>
<p>Try clearing the value to see the asyncronous validation at work.</p>
<p>Try swapping line 58 for 60 to change to syncronous validation, which propagates correctly.</p>
<hr />
<div><code>FormGroup valid = {{form.valid}}</code></div><br />
<div [formGroup]="form">
  <nested-control formControlName="nested"></nested-control>
</div>
<hr />
`
})
export class App {
  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.form = fb.group({
      nested: ['required']
    });
  }
}


@Component({
    selector: 'nested-control',
    providers: [{
        provide: NG_VALUE_ACCESSOR, 
        useExisting: forwardRef(() => NestedControl),
        multi: true
    }, {
        provide: NG_VALIDATORS,
        useExisting: forwardRef(() => NestedControl),
        multi: true,
    }],
    template: `
<div [formGroup]="form">
  <input type="text" formControlName="input" (keyup)="keyup($event)">
  <code>NestedControl valid = {{form.controls.input.valid}}, errors = {{form.controls.input.errors|json}}</code>
</div>
`
})
export class NestedControl implements ControlValueAccessor, Validator {
  form: FormGroup;
  private propagateChange = () => {};

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      // if we change the validation to be syncronous then everything works as expected:
      //input: [null, Validators.required]
      input: [null, null, this.asyncRequiredValidator]
    });
  }

  asyncRequiredValidator(control: AbstractControl): ValidationErrors {
    // run the built in required validator after 1 second
    return Observable.interval(1000).take(1).map(_ => {
      const result = Validators.required(control);
      console.log('result', result);
      return result;
    });
  }

  keyup() {
    this.propagateChange();
  }

  writeValue(v: any): void {
    this.form.setValue({ input: v });
  }

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {
  }

  validate(c: AbstractControl): ValidationErrors {
    return this.form.valid ? null : {invalid: true};
  }
}


@NgModule({
  imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ App, NestedControl ],
  bootstrap: [ App ]
})
export class AppModule {}
like image 246
Mike Chamberlain Avatar asked Apr 20 '17 12:04

Mike Chamberlain


1 Answers

There were a few issues which I finally figured out, but I'm not sure if this solution is optimal.

First, the component needs to provide NG_ASYNC_VALIDATORS rather than NG_VALIDATORS (although as usual I can't find this explicitly documented anywhere):

@Component({
    selector: 'nested-control',
    providers: [{
        provide: NG_ASYNC_VALIDATORS,  // <----- this
        useExisting: forwardRef(() => NestedComponent),
        multi: true,
    } ... 

Next, it should implement AsyncValidator rather than Validator:

export class NestedComponent implements ControlValueAccessor, AsyncValidator {
    ...
    validate(c: AbstractControl): Observable<ValidationErrors | null> {
        // must return result wrapped in Observable
        return Observable.of(this.form.valid ? null : {invalid: true});
    }   
}

Finally, upon validation, we must explicitly propagate the change. I had to use a setTimeout to ensure the state after running the validator is propagated, instead of the current. This seems hacky to me, so if anyone knows a better way then please let me know.

asyncRequiredValidator(control: AbstractControl): ValidationErrors {
    // run the built in required validator after 1 second
    return Observable.interval(1000).take(1).map(_ => {
      const result = Validators.required(control);
      console.log('result', result);
      setTimeout(() => this.propagateChange());   // <!---- propagate post-validation state
      return result;
    });
  }

Here is the Plunker with all this fixed:

http://plnkr.co/edit/6uSWVhdFgyHTvYjHlgmN?p=preview

like image 133
Mike Chamberlain Avatar answered Oct 02 '22 20:10

Mike Chamberlain