问题
I am trying to create a reactive form from indexes extracted from an array of data.
Lets say I have the following array:
array = [
{ name: 'Ali', gender: 'Male' },
{ name: 'Sara', gender: 'Female' }
];
I extracted the index as following:
this.result = new Set(this.array.flatMap(e => Object.keys(e), []));
this.result = Array.from(this.result);
And the result:
console.log(this.result)
// ["name", "gender"]
Now I need to loop over this.result
and create 2 form control names
with formControlName='name'
and for gender as well.
Once the loop is done and the form controls are created, I need to display it on screen. Here is a stackblitz about it.
回答1:
you can simple create a formGroup base of the array values now fieldFormItems
will be an array of formGroups
component
createForm() : void{
this.fieldForm = this.formBuilder.group({
fieldFormItems: this.formBuilder.array(
this.array.map(values =>{
return this.formBuilder.group(values)
})
)
})
}
template
<div [formGroup]="fieldForm">
<div formArrayName="fieldFormItems">
<div *ngFor="let fg of fieldForm.get('fieldFormItems').controls" [formGroup]="fg" >
<input formControlName="name">
<input formControlName="gender">
</div>
</div>
</div>
Updated ✨
get the form controls dynamically 🧙♂️
div [formGroup]="fieldForm">
<div formArrayName="fieldFormItems">
<div *ngFor="let fg of fieldForm.get('fieldFormItems').controls" [formGroup]="fg">
<ng-container *ngFor="let fc of fg.controls | keyvalue">
<input type="text" [formControl]="fc.value">
</ng-container>
</div>
</div>
</div
demo 🚀
来源:https://stackoverflow.com/questions/60925681/angular-9-how-to-generate-reactive-form-controls-automatically-from-indexes-extr