1
votes

I would like to know if there is any method that returns the fields that were changed in the form. I need to create a string list with the fields that have changed.

I own a very large form with about 30 fields.

One way would be to scroll through all the fields, but it would be a little painful as I have keys that hold an object and also have keys that hold a list of objects.

It would be nice if there was a function that would return all fields and objects that were changed on my form.

What is the right way to do this in Angular with Reactive Forms?

If possible write a code here, or tips on how you could be doing the validation of the fields that were changed on my form.

StackBlitz: https://stackblitz.com/edit/angular-khiusf

2
What have you tried so far ? can you share stacknlitz.. - programoholic
No, there is no such thing in reactive form. You just have to look into vanilla js on how to compare two objects, here's some options: stackoverflow.com/questions/8572826/… - AT82
At the moment I could not create any logic, I'm thinking about how to do this because I have a form with many fields, this would be a large object with keys that have another object as value. - Luiz Ricardo Cardoso
If you do: form.value.entries() and use lodash lodash.com/docs/#differenceBy, you can compare the form before and after changes. - Thomaz Capra

2 Answers

1
votes

Following method will return you the list of values which got changed :

getDirtyValuesForForm(formName: any) {
        let dirtyValues = {};

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

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

        return dirtyValues;
}

You can check controls for dirty-flag. Read form here https://angular.io/api/forms/FormControl

0
votes

If you save the initial form value, you can compare to know what changed.

You can see an example working here.