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)

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

3 Comments

ooooh love programming :-p. So how do I empty it first before I forEach? It is currently repeating the first email.
You can use removeAt(index) to remove item from FormArray
Thank you. I appreciate the help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.