【问题标题】:How to populate a form with array of data in Angular2?如何在 Angular2 中使用数据数组填充表单?
【发布时间】:2018-05-20 22:34:44
【问题描述】:

下面的 SO 问题帮助我设置了一个表单构建器、正确的验证以及来自 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)

【问题讨论】:

    标签: forms angular angular2-formbuilder formarray


    【解决方案1】:
    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));
    

    【讨论】:

    • 哦哦爱编程:-p。那么我如何在 forEach 之前先清空它?它目前正在重复第一封电子邮件。
    • 您可以使用removeAt(index)从FormArray中删除项目
    • 谢谢。我很感激帮助。 :)
    猜你喜欢
    • 2017-06-25
    • 2019-01-29
    • 2017-08-08
    • 2021-09-02
    • 2017-01-09
    • 2014-07-19
    • 2017-05-21
    • 2010-09-15
    • 2021-09-22
    相关资源
    最近更新 更多