I want to output a form in which one field is an array, and for each element of the array I need to output my inputs.
Component:
ngOnInit() {
const fb = this.fb;
this.editForm = this.fb.group({
country: fb.control(null),
identifiers: this.fb.array([
this.fb.group({
codeIdentifier: fb.control(null),
numIdentifier: fb.control(null),
})
]),
});
this.organizationService.getOneById(this.id).subscribe((organization: Organization) => {
let ids: any[] = [];
organization.identifiers.forEach(item => {
let id: any = { "codeIdentifier": "", "numIdentifier": "" };
id.codeIdentifier = item.typeIdentifier.code;
id.numIdentifier = item.numIdentifier;
ids.push(id);
});
this.editForm.setControl('identifiers', this.fb.array(ids || []));
})
}
HTML:
<div [formGroup]="editForm">
<ng-container formArrayName="identifiers">
<ng-container *ngFor="let identifier of identifiers.controls; let i=index" [formGroupName]="i">
<input type="text" formControlName="codeIdentifier">
<input type="text" formControlName="numIdentifier">
</ng-container>
</ng-container>
</div>
Got error:
Cannot find control with path: 'identifiers -> 0 -> codeIdentifier'
Pay attention to set it with the group
inside the array
as you built it, like that:
this.editForm.setControl('identifiers',
this.fb.array(ids.map(
id => this.fb.group({codeIdentifier: id})
) || [])
);
this.editForm.setControl('identifiers',
this.fb.array(ids.map(
id => this.fb.group({numIdentifier: id})
) || [])
);
Objects
structure, but this is the way to build the Control Array back to view for Edit/Update purposes.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With