0

I am using Angular 5 and reactive forms. My requirement is simple:

I have a form which gets pre-populated using an object. I store object in a userObj and form values later are stored in payload variable. I want to compare these two objects and want to conclude that form is being changed or not.

Form Controls:

firstNameControl = new FormControl('', Validators.required);
  lastNameControl = new FormControl('', Validators.required);
  phoneControl = new FormControl('', Validators.required);
  emailControl = new FormControl('', Validators.required);

Form object:

    userForm: FormGroup;

  this.userForm = new FormGroup({
  firstNameControl: this.firstNameControl,
  lastNameControl: this.lastNameControl,
  emailNameControl: this.emailControl,
  phoneControl: this.phoneControl
 });

I get form prepopulated using below object:

 let userObj = {
            "user":{
                "profile":{
                    "details":
                    {
                        "firstname":'xyz',
                        "lastname":"abc",
                        "phone":"99987777"
                        "email":"email@gmail.com"

                    }
                }
            }

        } 

So while submitting form I want to check whether userObj and payload is same

  let payload = {
                "user":{
                "profile":{
                    "details":
                    {
                        "firstname": this.firstnameControl
                        "lastname": this.lastnameControl
                        "phone": this.phoneControl.value
                        "email": this.emailControl.value

                    }
                }
            }
    }

I tried comparing using JSON.stringify but it did not work.

I have more key values and form controls in actual.

Always_a_learner
  • 4,585
  • 13
  • 63
  • 112

1 Answers1

0

You can't use simple JSON.stringify there. You have to do deep object comparison as this link

You can use object comparison function for achieve your goal.I have done a example for you. stackblitz

Asanka
  • 1,628
  • 1
  • 10
  • 20