I have an angular component corresponding a form/page that is generating an indeterminate amount of child components, each representing an individual field, and I would like
The problem here is, that it is not possible to have the same form control name multiple times in one form group.
You need to declare an own form group for each child component and then you can iterate over it in the parent component based on your reference attribute. You can get each child form control with the directive component method FormGroupDirective.getControl(controlName)
as you can see in documentation: https://angular.io/docs/ts/latest/api/forms/index/FormGroupDirective-directive.html
There are a couple of things I came across implementing this in a Plunker.
First, we'll need to pass in our formGroup from the parent to the child so we have a FormGroup to satisfy the templating engine's enforcement of FormControls being a part of a FormGroup:
child.component.ts
@Input() parentGroup: FormGroup;
child.component.html
<td [formGroup]="parentGroup">
<...>
</td>
Then we'll also need to set the [formControl]
or evaluate property.id
, otherwise it looks for the name "property.id":
<input type="text " class="form-control" [ngClass]="{error: !options.valid}" [formControl]="options"/>
or
<input type="text " class="form-control" [ngClass]="{error: !options.valid}" formControlName="{{property.id}}"/>
Your code was using different variables binding the formGroup
and using formAttrs
which was a little unclear as to what was going on so I went ahead and collapsed them to one and you can see that in the Plunker: http://plnkr.co/edit/3MRiO9bGNFAkN2HNN7wg?p=preview