Search code examples
angularangular-reactive-formsformarray

Angular Reactive Form - Render control in form array for a string array


I have a string array of emails as below:

{
   "streetName": "street 1",
   "emails" : [
     "[email protected]",
     "[email protected]"
   ]
}

How would I render this in reactive form input fields?

I tried this but not working:

<div class="row mt-4" formArrayName="emails">
  <div class="col" *ngFor="let email in myform.get('emails')['controls']; let emailIndex=index">
    <input type="text" placeholder="" formControlName="emailIndex"/>
  </div>
</div>

Solution

    1. The problem was the *ngFor part. You have to use of for [ngForOf] directive. And pass the emailIndex with [formControlName] attribute.
    <div
      class="col"
      *ngFor="
        let email of myform.get('emails')['controls'];
        let emailIndex = index
      "
    >
      <input type="text" placeholder="" [formControlName]="emailIndex" />
    </div>
    
    1. Besides, you should also look for the component part for the way how you patch the control. You need to iterate each value in the data.emails array and add the FormControl to emails FormArray.
    for (let index in this.data.emails) {
      (this.myform.controls.emails as FormArray).controls.push(
        new FormControl(this.data.emails[index])
      );
    }
    

    Demo @ StackBlitz