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

本小妞迷上赌 提交于 2019-12-12 09:59:09

问题


The SO question below helped me setup a formbuilder, proper validation, and a dynamic set of input fields from a formBuilder Array.

How to assign and validate arrays to forms in Angular2

Note this solution code http://plnkr.co/edit/YoqdBEo0MihaxdhHH1FV?p=preview

Everything works great on a new form, but I get stuck when trying to populate said form from the database.

I'm using the following code and initialValue has multiple emails saved from this form in a previous transaction. All my other form fields work perfectly. I'm just not sure how to operate on an array.

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

If I keep the lines commented only the first email in the array shows properly in the form.

If i uncomment the lines and try to refresh the emailsCtrl w/ the new list of emails. I get the following error.

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:


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

The FormArray should be this.emailsCtrl other than this.emailCtrl The formArrayName is emails and the formControlName is email

You can access it based on the name:

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


来源:https://stackoverflow.com/questions/47684564/how-to-populate-a-form-with-array-of-data-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!