Kirby
Kirby

Reputation: 2008

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

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)

Upvotes: 2

Views: 778

Answers (1)

Haifeng Zhang
Haifeng Zhang

Reputation: 31895

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

Upvotes: 1

Related Questions