您需要创建一个数组数组。一不小心很容易迷失自我,但有些像:
constructor(private fb: FormBuilder) {
this.myForm=this.createForm(this.orders); //I like pass the argument
}
createForm(orders:any) //Our form has only an arrayForm "data"
{
return this.fb.group(
{
data:this.fb.array(this.createOrders(orders))
}
)
}
createOrders(orders:any)
{
//using map, with each "order" we create a formGroup, so we return a formGroup[]
return orders.map(x=>
{
return this.fb.group({
id: x.id,
name: x.name,
address: x.adress,
materials:this.fb.array(this.createMaterial(x.materials)) //<--call a function
})
})
}
createMaterial(materials:any) //like the above function return a fromGroup[]
{
return materials.map(x=>{
return this.fb.group({material_id: x.id,material_name: x.name, quantity: x.qty})
})
}
模板就像
<form class="form-horizontal" [formGroup]="myForm" (ngSubmit)="onCreateProduct()" >
<div class="card" formArrayName="data">
<div class="card-block"
*ngFor="let category of myForm.get('data').controls;let i=index">
<!--see that to show the name of categorie we are using the array categories
this are not included in the myForm, it's the "variable" categories-->
CATEGORY: {{ categories[i].name }}
<br>
<table class="table" [formGroupName]="i" >
<thead>
<tr>
<th>Material ID</th>
<th>Material Name</th>
<th>Qty</th>
<th>Action</th>
</tr>
</thead>
<tbody formArrayName="materials">
<tr *ngFor="let row of category.get('materials').controls; let j = index" [formGroupName]="j">
<td>{{row.value.material_id}}</td>
<td>{{row.value.material_name}}</td>
<td>{{row.value.quantity}}</td>
<td><button type="button" (click)="onDeleteRow(i,j)"> <i class="icofont icofont-ui-delete"></i> Remove</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</form>