简体   繁体   中英

Check if a field has been modified with angular 6 and firestore

I have a form for editing a user details, where it should check if the user has make modification if not then don't make changes. Currently am using if to check which is working but I still feel is not effective way for this, because I have multiple fields which have to check each of them which makes the code repetitive and huge.

    if (f.value.first_name) {
        this.user.firstName = f.value.first_name;
    }

I have tried using elvis operator but it's not working for me

this.user.firstName ?  this.user.firstName :f.value.first_name;

Is there any other effective way to do this?

You can loop through each form controls and check if they are dirty (modified).

Object.keys(f.controls).forEach((key: string) => {
        if (f.get(key).dirty) {
            this.user[key] = f.get(key).value
        }
});

I keep a copy of the original object and then do this:

get isDirty(): boolean {
    return JSON.stringify(this.originalProduct) !== JSON.stringify(this.currentProduct);
}

I stringify the copy of the original product (before edits) and the current product and compare them. I assume if they are not equal that something changed.

There are some caveats to this approach, especially if your object structure is complex as there may be cases that stringify does not create the strings exactly the same. But I have not run into this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM