在Angular中使用formArray修补formGroup中的值?

时间:2019-09-19 07:05:42

标签: angular angular-reactive-forms

https://stackblitz.com/edit/angular-fzgtqc?file=src%2Fapp%2Fapp.component.ts 可复制的示例

这是我正在https://stackblitz.com/edit/angular-fzgtqc?file=SampleData上工作的示例数据

app.component.ts

editTrainner(trainner: Trainner) {
    this._trainnerservice.currentTrainner = Object.assign({}, trainner);
    this.registrationForm.patchValue({
          personal_details: { type: Object,
            name: { type: Object,
                first_name: this._trainnerservice.currentTrainner.personal_details.name.first_name,
                last_name: this._trainnerservice.currentTrainner.personal_details.name.last_name
            },
            dob: this._trainnerservice.currentTrainner.personal_details.dob,
            about_yourself: this._trainnerservice.currentTrainner.personal_details.about_yourself,
            languages_known: this.fb.array([this.addlanguages_known()]),
            willingly_to_travel: this._trainnerservice.currentTrainner.personal_details.willingly_to_travel
        }
    });
  }
  addlanguages_known(): any {
    const control = this.registrationForm.get('languages_known') as FormArray;
    this._trainnerservice.currentTrainner.personal_details.languages_known.forEach(x => {
        control.push(this.fb.control(''));
      });
  }

在执行代码时出现错误:“ 无法读取null的属性'push'

我想在用户单击编辑按钮时将Form数组数据推入表单。

1 个答案:

答案 0 :(得分:1)

首先,您应该从patchValue内部删除用于从formarray设置值的函数。而是照原样调用函数addlanguages_known()。然后,您到formarray的路径不正确。您的formarray位于personal_details内部,因此请正确执行以下操作:

addlanguages_known(): any {
  const control = this.registrationForm.get('personal_details.languages_known') as FormArray;
  this._trainnerservice.currentTrainner.personal_details.languages_known.forEach(x => {
    control.push(this.fb.control(x));
  });
}

并且如上所述,从editTrainner()中删除以下行:

languages_known: this.fb.array([this.addlanguages_known()]),

Your forked STACKBLITZ

PS:无关,但您使用的是某种通用类型的Object,则应根据模型键入数据。