8

I'm trying to create a dynamic form group, im trying to achieve this

enter image description here

on add more click add 2 dynamic fields im calling this function:

onAddSurgeries(){
    const control = new FormGroup({
        'surgery': new FormControl(null),
        'illness': new FormControl(null)
    });
      (<FormArray>this.form.get('surgeries')).push(control);
}

and this is how my html looks like:

<tr *ngFor="let ctrl of form.get('surgeries')['controls']; let i = index">
   <td><input type="text" class="form-control" [formControlName]="ctrl['controls'].surgery"></td>
   <td><input type="text" class="form-control" [formControlName]="ctrl['controls'].illness"></td>
</tr>

I know the mistake I am doing, formControlName shouldn't be "ctrl['controls'].surgery" I am supposed to put "i" as formcontrolname when i have only one formcontrol instead of 2 controls in a formgroup, but in this case i don't know what should i enter in the formControlName because when i submit the form the values of both inputs are empty because it is not synced with the formgroup controls

1 Answer 1

9

You are missing (at least from question) the marking of the formArrayName. Also you are pushing formgroups to your formarray, which in template need to be marked with the index value in your iteration. Then your formControlNames are just the names you have specified, i.e surgery and illness:

<table>
  <ng-container formArrayName="surgeries">
    <tr *ngFor="let ctrl of form.get('surgeries')['controls']; let i = index" 
      [formGroupName]="i">
      <td><input type="text" class="form-control" formControlName="surgery"></td>
      <td><input type="text" class="form-control" formControlName="illness"></td>
    </tr>
  </ng-container>
</table>

DEMO

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

1 Comment

i knew i was missing something, thank you so much for pointing out :) it worked

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.