如何在Angular2中填充包含数据数组的表单?

时间:2017-12-06 22:30:16

标签: forms angular angular2-formbuilder formarray

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

How to assign and validate arrays to forms in Angular2

请注意此解决方案代码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)

1 个答案:

答案 0 :(得分:1)

this.emailCtrl = this.fb.array([], Validators.minLength(1));
this.emails.forEach((email: any) => this.addEmail(email));

this.emailsCtrl以外,FormArray应为this.emailCtrl    formArrayName是电子邮件,formControlName是电子邮件

您可以根据名称访问它:

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