Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Dynamic form group

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

like image 910
Wasif Khalil Avatar asked Nov 09 '17 18:11

Wasif Khalil


1 Answers

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

like image 99
AT82 Avatar answered Sep 28 '22 06:09

AT82