30 seconds of angular
Star
✨✨ New to Angular? Check out interactive Angular Codelab ✨✨

Accessing all nested form controls

Sometimes we need to work with every single Control is a form. Here's how it can be done:

function flattenControls(form: AbstractControl): AbstractControl[] {
  let extracted: AbstractControl[] = [ form ];
  if (form instanceof FormArray || form instanceof FormGroup) {
    const children = Object.values(form.controls).map(flattenControls);
    extracted = extracted.concat(...children);
  }
  return extracted;
}

For examples use:

// returns all dirty abstract controls
extractControls(form).filter((control) => control.dirty);

// mark all controls as touched
extractControls(form).forEach((control) => 
    control.markAsTouched({ onlySelf: true }));

Links

Interactive demo