Angular form updateValueAndValidity of all children controls

Francesco Borzi picture Francesco Borzi · Oct 28, 2017 · Viewed 26.6k times · Source

In my Angular 4 app, I have a form with several controls.

At some points I need to force the update of their validity, so I'm doing:

this.form.get('control1').updateValueAndValidity();
this.form.get('control2').updateValueAndValidity();
this.form.get('control3').updateValueAndValidity();
// and so on....

and then:

this.form.updateValueAndValidity();

this works fine.

However I was wondering if there is a better way to accomplish the same thing, by just calling one method on the parent form.

According to its documentation, the updateValueAndValidity() method:

By default, it will also update the value and validity of its ancestors.

but in my case I need to update the value and validity of its descendants. So I can get rid of many lines of code.

Answer

Ravi Anand picture Ravi Anand · Jan 7, 2020

I had the same situation for me to update FormGroup | FormArray at nested level controls.

check this out(worked for me):

/**
 * Re-calculates the value and validation status of the entire controls tree.
 */
function updateTreeValidity(group: FormGroup | FormArray): void {
  Object.keys(group.controls).forEach((key: string) => {
    const abstractControl = group.controls[key];

    if (abstractControl instanceof FormGroup || abstractControl instanceof FormArray) {
      updateTreeValidity(abstractControl);
    } else {
      abstractControl.updateValueAndValidity();
    }
  });
}