1

I have a form group and then I map the values on the form to my object type to make a request to edit the item.

Form:

  public companyForm = new FormGroup(
    {
      generalInfo: new FormGroup({
        name: new FormControl('', [Validators.required, Validators.maxLength(this.maxLength)]),
        active: new FormControl(false)
      }),
      address: new FormGroup({
        street: new FormControl('', [Validators.required, Validators.maxLength(this.maxLength)]),
        streetNumber: new FormControl('', [Validators.required]),
        postalCode: new FormControl('', [Validators.required]),
        city: new FormControl('', [Validators.required]),
        country: new FormControl('', [Validators.required])
      })
   })

CompanyEdit object:

      name: formValue.generalInfo.name,
      active: formValue.generalInfo.active,
      address: {
        street: formValue.address.street,
        city: formValue.address.city,
        streetNumber: formValue.address.streetNumber,
        postalCode: formValue.address.postalCode
      },
      country: formValue.address.country

The fields names and the way they are nested are not compatible. While editing, I like to send only the changed controls on the form. What would be the best way to achieve acquiring the dirty controls and map them to my object type?

AtlasB
  • 21
  • 1
  • 4

1 Answers1

0

You can check form if there is a dirty values in formGroup.

There is a answer from similar question on stackoverflow URL. I will copy/paste the code here for you.

  getDirtyValues(form: any) {
        let dirtyValues = {};

        Object.keys(form.controls)
            .forEach(key => {
                const currentControl = form.controls[key];

                if (currentControl.dirty) {
                    if (currentControl.controls)
                        dirtyValues[key] = this.getDirtyValues(currentControl);
                    else
                        dirtyValues[key] = currentControl.value;
                }
            });

        return dirtyValues;
}
Daniel Vágner
  • 538
  • 3
  • 19