Angular2: How do you mark FormGroup control dirty via `patchValue()`

I usually do this:

this.formControl.markAsDirty()

Or in your case it could be:

this.myForm.get('incidentDate').markAsDirty()

If you have a group or array that you need to mark as dirty you can use this

export class Helpers {
/**
   * Loop and touch all it has
   *
   * @param {FormGroup} formGroup
   * @param func << function name: [markAsTouched, markAsUntouched, markAsDirty, markAsPristine, markAsPending
   * @param opts
   *
   */
  public static touchAll(formGroup: FormGroup|FormArray, func = 'markAsDirty', opts = {onlySelf: false}): void {
    mapValues(formGroup.controls, (c, i) => {
      if (c instanceof FormGroup || c instanceof FormArray)
        Helpers.touchAll(c, func, opts);
      else
        c[func](opts);
    })
  }
}

You can use the SuperForm npm package to do that for you.


mark as dirty controls(only those with value) inside FormGroup

  markDirtyAllControlsWithValue(form: FormGroup): void {
    const recursiveFunc = (formGroup: FormGroup) => {
      Object.keys(formGroup.controls).forEach(field => {
        const control = formGroup.get(field);
        if (control.value !== null && control.value !== undefined && control.value !== '') {
          control.markAsDirty();
        }
        if (control instanceof FormGroup) {
          recursiveFunc(control);
        }
      });
    };
    recursiveFunc(form);
  }

Tags:

Angular