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

1

2

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)
Embrue answered 6/12, 2017 at 22:30 Comment(0)
H
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));
Hervey answered 6/12, 2017 at 22:59 Comment(3)
ooooh love programming :-p. So how do I empty it first before I forEach? It is currently repeating the first email.Embrue
You can use removeAt(index) to remove item from FormArrayHervey
Thank you. I appreciate the help. :)Embrue

© 2022 - 2024 — McMap. All rights reserved.