Useful Development

Angular Forms: how to get only the changed values

posted on Jun 4, 2019

I had a requirement to record the changes made by the user through a reactive form. Previously I would have just compared the original form data with the updated form values but I decided to have a look at using the dirty property on the form's FormControls instead. It worked pretty well so I thought I would share the code.

There is a built in method on a FromGroup getRawValue that can be used to get the value of a FormGroup but no method to get only the changed values. To do that the following the function below needs to iterate through all the children of the top level FormGroup and find the values of any dirty form controls. The function calls itself recursively when it finds a child FormGroups or FromArrays.

    
  private getUpdates(
    formItem: FormGroup | FormArray | FormControl,
    updatedValues: any,
    name?: string
  ) {
    if (formItem instanceof FormControl) {
      if (name && formItem.dirty) {    
        updatedValues[name] = formItem.value;
      }
    } else {
      for (const formControlName in formItem.controls) {
        if (formItem.controls.hasOwnProperty(formControlName)) {
          const formControl = formItem.controls[formControlName];

          if (formControl instanceof FormControl) {
            this.getUpdates(formControl, updatedValues, formControlName);
          } else if (
            formControl instanceof FormArray &&
            formControl.dirty &&
            formControl.controls.length > 0
          ) {
            updatedValues[formControlName] = [];
            this.getUpdates(formControl, updatedValues[formControlName]);
          } else if (formControl instanceof FormGroup && formControl.dirty) {
            updatedValues[formControlName] = {};
            this.getUpdates(formControl, updatedValues[formControlName]);
          }
        }
      }
    }
  }
    

A demo is available below on StackBlitz:

angular-reactive-forms
angular