检查反应式表单值是否从初始值更改

RAH*_*NDU 20 typescript angular

我有一个包含 3 个控件的反应式表单,我想检测表单的更改。我已经创建了一个表单的值更改方法并订阅了它,但是。现在,每当它的任何控制值发生变化时,就会发出事件。

如果用户向这 3 个控件的 ant 添加了任何值并尝试退出页面,那么我想提示一个模式,表单中存在未保存的更改。

我怎样才能检查表单更改时发出的值是否不同于其初始值?

public createGroupForm : FormGroup;

ngOnInit() {
  this.createGroupForm = this._formBuilder.group({
      groupName: new FormControl("", [Validators.required]),
      groupPrivacy: new FormControl(null, [Validators.required]),
      groupTagline: new FormControl('')
  });

  this.onCreateGroupFormValueChange();
}


onCreateGroupFormValueChange(){
    this.createGroupForm.valueChanges.subscribe(value => {
      console.log(value);
      //emitting every time if any control value is changed
    });
}
Run Code Online (Sandbox Code Playgroud)

小智 36

您必须每次发出订阅时检查表单值的初始值,并在需要时使用 hasChange

public createGroupForm : FormGroup;
hasChange: boolean = false;

ngOnInit() {
  this.createGroupForm = this._formBuilder.group({
      groupName: new FormControl("", [Validators.required]),
      groupPrivacy: new FormControl(null, [Validators.required]),
      groupTagline: new FormControl('')
  });

  this.onCreateGroupFormValueChange();
}


onCreateGroupFormValueChange(){
    const initialValue = this.createGroupForm.value
    this.createGroupForm.valueChanges.subscribe(value => {
      this.hasChange = Object.keys(initialValue).some(key => this.form.value[key] != 
                        initialValue[key])
    });
}
Run Code Online (Sandbox Code Playgroud)