代码之家  ›  专栏  ›  技术社区  ›  Vladimir Humeniuk

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

  •  0
  • Vladimir Humeniuk  · 技术社区  · 5 年前

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

    如何检查,输入中的初始值是否改变?因为当我使用 userInfoForm.dirty 它返回true,即使我从值中删除1个符号,然后再添加回来。

    0 回复  |  直到 5 年前
        1
  •  0
  •   Prashant Pimpale Dila Gurung    5 年前

    我想这样做,会用的 valueChanges() 表格控制方法 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

        2
  •  0
  •   Drenai    5 年前

    form.value 在创建之后,使用- this.initialFormValue = JSON.stringify(this.form.value)

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