Angular Reactive forms : how to get just changed values

AHméd Net picture AHméd Net · Dec 4, 2018 · Viewed 10.6k times · Source

Im building a reactive forms using angular 6, this form contain 3 attributes (name,age,phone) and i would to get just the changed values not all form values.

this.refClientForm = this.formBuilder.group({
  name: [],
  phone: [],
  age: []
});

for the form listener :

 this.refClientForm.valueChanges.subscribe(values => console.log(values))

but i got always all form values.

Answer

J. Knabenschuh picture J. Knabenschuh · Dec 4, 2018

You can check all controls for dirty-flag. See https://angular.io/api/forms/FormControl

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

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

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

        return dirtyValues;
}