【问题标题】:Angular Reactive forms : how to get just changed valuesAngular Reactive forms:如何获取刚刚更改的值
【发布时间】:2018-12-04 13:13:37
【问题描述】:

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

this.refClientForm = this.formBuilder.group({
  name: [],
  phone: [],
  age: []
});

对于表单监听器:

 this.refClientForm.valueChanges.subscribe(values => console.log(values))

但我总是得到所有表单值。

【问题讨论】:

标签: angular forms reactive


【解决方案1】:

您可以检查所有控件的脏标志。见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;
}

【讨论】:

  • 控件对象不是数组
  • 是的,你是对的。我更新了帖子。但想法是一样的。当然,您也可以通过for in 或类似的方式遍历控件对象,然后您也可以得到名称。
【解决方案2】:

有一种简单的方法可以检查响应式表单中是否有任何控件脏。

getUpdatedValues() {
 const updatedFormValues = {};
 this.form['_forEachChild']((control, name) => {
  if (control.dirty) {
      this.updatedFormValues[name] = control.value;
  }
});
console.log(this.updatedFormValues);

【讨论】:

  • 使用_forEachChild不是很好的做法,其他答案是正确的。
【解决方案3】:

在这里找到更好的答案:

Angular 2 Reactive Forms only get the value from the changed control

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);
    }
  );

【讨论】:

    【解决方案4】:

    将pairwise() 运算符与startWith(this.refClientForm.value) 运算符一起使用 然后表单 valueChanges 将在第一次尝试时发出

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2015-11-09
    • 2018-08-24
    • 1970-01-01
    • 2017-10-17
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多