I'm getting a list of objects with a display name & display value from the backend which changes depending on different requests. I can display this information using a simple *ngFor ... {{object.displayName)): {{object.value}}... But I need to make this page into a form. So my question is how can I create x number of FormControls each with {{object.displayName}} as it's value? And then use the above for loop to match the displayName with the FormControl. I've looked at using a FormArray but couldn't create one dynamically
You need to create an empty FormArray, then iterate the data from backend and push FormCntrols.
form: FormGroup;
dataFromBackend: [];
constructor(private formBuilder: FormBuilder) { }
this.form = this.formBuilder.group({
array: this.formBuilder.array([
])
});
ngOnInit() {
const control = <FormArray>this.form.get('array');
for (const item of dataFromBackend) {
control.push(new FormControl(item));
}
}
EDIT
Adding HTML
<form [formGroup]="form">
<table>
<thead>
<th>Name</th>
<th>Value</th>
</thead>
<ng-container formArrayName="ponderacionFactor">
<tbody *ngFor="let item of form.get('array')['controls']; let i = index" [formGroupName]="i">
<td>{{item.name}}</td>
<td>{{item.value}}</td>
</tbody>
</ng-container>
</table>
</form>