如何在 Angular2 中用数据数组填充表单?

How to populate a form with array of data in Angular2?

下面的 SO 问题帮助我设置了一个 formbuilder、正确的验证以及来自 formBuilder 数组的一组动态输入字段。

注意这个解决方案代码http://plnkr.co/edit/YoqdBEo0MihaxdhHH1FV?p=preview

在新表单上一切正常,但我在尝试从数据库填充所述表单时遇到问题。

我正在使用以下代码,并且 initialValue 在之前的交易中从该表单保存了多封电子邮件。我的所有其他表单字段都完美无缺。我只是不确定如何对数组进行操作。

ngOnChanges(changes: SimpleChanges): void {
  if(this.form && changes['initialValue']){
    this.emails = changes['initialValue'].currentValue.emails;
    this.form.patchValue(changes['initialValue'].currentValue);
    //console.log('emails are now', this.emails);
    //this.emailCtrl = this.fb.array([], Validators.minLength(1));
    //this.emails.forEach((email: any) => this.addEmail(email));
  }
}

如果我保留注释行,则只有数组中的第一封电子邮件会在表单中正确显示。

如果我取消注释这些行并尝试使用新的电子邮件列表刷新 emailsCtrl。我收到以下错误。

ERROR Error: Cannot find control with path: 'emails -> 1 -> email'
at _throwError (forms.js:2385)
at setUpControl (forms.js:2255)
at FormGroupDirective.addControl (forms.js:6606)
at FormControlName._setUpControl (forms.js:7256)
at FormControlName.ngOnChanges (forms.js:7169)
at checkAndUpdateDirectiveInline (core.js:12092)
at checkAndUpdateNodeInline (core.js:13598)
at checkAndUpdateNode (core.js:13541)
at debugCheckAndUpdateNode (core.js:14413)
at debugCheckDirectivesFn (core.js:14354)
this.emailCtrl = this.fb.array([], Validators.minLength(1));
this.emails.forEach((email: any) => this.addEmail(email));

FormArray 应该是 this.emailsCtrl 而不是 this.emailCtrl formArrayName 是 emails,formControlName 是 email

您可以根据名称访问:

  this.emailsCtrl = this.form.get('emails') as FormArray;
  this.emails.forEach(email => this.addEmail(email));