如何检查表单中的值是否已从初始值更改

How to check is value in form was changed from initial

我的 Angular 7 应用程序中有反应形式:

  this.userInfoForm = this.formBuilder.group({
      displayName: [this.user.displayName, [
        Validators.required,
      ]],
    })

如何检查输入的初始值是否被更改?因为当我使用 userInfoForm.dirty 时它 return 是真的,即使我从值中删除 1 个符号然后再将其添加回去。

实现此目的的一种方法是获取表单的值,form.value 在表单创建后,并使用类似 - this.initialFormValue = JSON.stringify(this.form.value)

的方式保存它

每当您想检查表单是否已更改时,例如提交时,获取当前值 JSON.stringify(this.form.value) 并与 this.initialFormValue

进行比较

您无法通过比较原始模型和 form.value 来可靠地进行测试,因为在许多情况下,模型上的数字将作为字符串返回,并且表单基础对象的顺序可能与型号

我还没有测试过这个,但理论上它应该可以工作!!

我会这样做,将使用 FormControl 的 valueChanges() 方法,其中 returns 一个发出最新值的 Observable。因此,您可以订阅 valueChanges 来更新实例变量或执行操作。

intialValue: any; // Define one property to store the initial value of the control

this.intialValue = this.userInfoForm.get('displayName').value; // Store initial value

// and then subscribe to valueChanges method of FormControl to get the latest value
this.userInfoForm.get('displayName').valueChanges.subscribe(value => {
  console.log('Intital Value', this.intialValue)
  console.log('New Value', value);
})

Working Demo