0

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>
0

1 Answer 1

3
  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

Sign up to request clarification or add additional context in comments.

3 Comments

for me it is rendering as [object Object]
Which part that render the [object Object]? Can you create a demo in StackBlitz? Thanks.
I go the issue, I am adding FormGroup instead of FormControl, your code is correct

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.