首页 > 解决方案 > 我们如何检查最终用户是否未更改预填充?

问题描述

我正在使用 Angular 5 和反应形式。我的要求很简单:

我有一个使用对象预先填充的表单。我将对象存储在 userObj 中,稍后将表单值存储在有效负载变量中。我想比较这两个对象,并想得出结论是否正在改变形式。

表单控件:

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

表单对象:

    userForm: FormGroup;

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

我使用以下对象预填充了表单:

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

                    }
                }
            }

        } 

所以在提交表单时我想检查 userObj 和 payload 是否相同

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

                    }
                }
            }
    }

我尝试使用 JSON.stringify 进行比较,但没有奏效。

实际上我有更多的键值和表单控件。

标签: jsonangularangular-reactive-forms

解决方案


你不能在那里使用简单的 JSON.stringify 。您必须像此链接一样进行深度对象比较

您可以使用对象比较功能来实现您的目标。我为您做了一个示例。 堆栈闪电战


推荐阅读