Search code examples
angulartypescriptangular2-formsangular-reactive-formsangular-forms

Angular updates validity of existing FormArray elements when new element is added


And I don't want this. Because I'm validating each element of FormArray asynchronously, I want validators only to run when necessary (i.e. when value of the control they're added to really changes). I also find this behaviour strange because validators don't get executed when value of FormArray changes, only when new element is added.

replication: https://stackblitz.com/edit/angular-reactive-forms-tkdu1n?file=app%2Fapp.component.ts

Any help would be greatly appreciated


Solution

  • It appears that FormArray executes the validator for every nested FormControl when a new FormControl is pushed inside it, and there's nothing to do about it...

    So I forked your stackblitz and I created a stateful validator with a closure, and it did the trick:

    form: FormArray;
    
    ngOnInit() {
      this.form = new FormArray([]);
      this.form.push(new FormControl("test", null, this.validatorFactory()));
    }
    
    addControl() {
      this.form.push(new FormControl(null, null, this.validatorFactory()));
    }
    
    validatorFactory() {
      let previousValue;
      return (c: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
        if (c.value == previousValue) {
          return Observable.of(null);
        } else {
          previousValue = c.value;
          return Observable.of(null).delay(1000);
        }
      };
    }
    

    Forked Stackblitz

    Hope this helps!