Angular Reactive forms : how to get just changed values

0

Issue

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.

Solution

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;
}

Answered By – J. Knabenschuh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More