Angular Reactive 表单:如何获取刚刚更改的值

AHm*_*Net 6 forms reactive angular

我使用 angular 6 构建了一个反应式表单,该表单包含 3 个属性(姓名、年龄、电话),我只想获取更改后的值而不是所有表单值。

this.refClientForm = this.formBuilder.group({
  name: [],
  phone: [],
  age: []
});
Run Code Online (Sandbox Code Playgroud)

对于表单侦听器:

 this.refClientForm.valueChanges.subscribe(values => console.log(values))
Run Code Online (Sandbox Code Playgroud)

但我总是得到所有形式的价值。

J. *_*huh 11

您可以检查脏标志的所有控件。见https://angular.io/api/forms/FormControl

getDirtyValues(form: any) {
        let dirtyValues = {};

        Object.keys(form.controls)
            .forEach(key => {
                let currentControl = form.controls[key];

                if (currentControl.dirty) {
                    if (currentControl.controls)
                        dirtyValues[key] = this.getDirtyValues(currentControl);
                    else
                        dirtyValues[key] = currentControl.value;
                }
            });

        return dirtyValues;
}
Run Code Online (Sandbox Code Playgroud)


kta*_*lyn 7

在这里找到更好的答案:

Angular 2 Reactive Forms 仅从更改的控件中获取值

this.imagSub = this.imagingForm.valueChanges.pipe(
    pairwise(),
    map(([oldState, newState]) => {
      let changes = {};
      for (const key in newState) {
        if (oldState[key] !== newState[key] && 
            oldState[key] !== undefined) {
          changes[key] = newState[key];
        }
      }
      return changes;
    }),
    filter(changes => Object.keys(changes).length !== 0 && !this.imagingForm.invalid)
  ).subscribe(
    value => {
      console.log("Form has changed:", value);
    }
  );
Run Code Online (Sandbox Code Playgroud)