Reputation: 2247
I'm trying to create a dynamic form group, im trying to achieve this
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
Upvotes: 8
Views: 10868
Reputation: 73357
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 formControlName
s 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>
Upvotes: 9