Angular 4使用反应形式在数组内部创建动态formArray [英] Angular 4 Create Dynamic formArray inside array using reactive forms
问题描述
在这里,我们正在动态创建表单数组的内部数组.
Here, we are creating dynamically form array's inside array.
下面是预期结果的样本结构.
Below is the sample structure of expected result given below.
{
"optionsRadios": null,
"Package_Title": null,
"HotelData": [
{
"Htitle": "",
"HDescription": "",
"hotelStar": "",
"RoomData": [
{
"Hotel_Room_Type": ""
},
{
"Hotel_Room_Type": ""
}
]
}
]
}
我想动态创建HotelData,在该HotelData数组中,我也想动态创建RoomData数组字段.
I want to create HotelData Dynamically, within that HotelData array i want to create RoomData array fields also dynamically.
我通过以下代码创建了HotelData字段:
I created HotelData fields by the following codes:
export class AddPackageComponent implements OnInit {
ngOnInit() {
this.invoiceForm = this._formBuild.group({
Package_Title: [],
HotelData: this._formBuild.array([this.addRows()])
})
}
addRows() {
return this._formBuild.group({
Htitle: [''],
HDescription: [''],
hotelStar: ['']
});
}
addHotel() {
const control: FormArray = this.invoiceForm.get(`HotelData`) as FormArray;
control.push(this.addRows());
}
}
推荐答案
您在正确的轨道上,我们只需要添加更多代码即可.
You are on the right track, we just need to add some more code...
addRows
需要表单数组RoomData,在这里,我们最初还会推送一个空的房间表单组.如果您不想这样做,请对其进行修改.
addRows
need the form array RoomData, and here we also initially push an empty form group of room. If you don't want that, modify it.
addRows() {
let group = this._formBuild.group({
...
RoomData: this._formBuild.array([])
});
// push formgroup to array initially
this.addRoom(group.controls.RoomData)
return group;
}
addRoom
看起来像这样:
addRoom(hotel:any) {
let group = this._formBuild.group({
Hotel_Room_Type: ['']
})
hotel.push(group)
}
当要向酒店添加新房间时,
addRoom
也是我们从模板调用的方法.请记住,将当前酒店作为模板中的参数传递.
addRoom
is also the method we are calling from template when we want to add a new room to a hotel. Remember to pass the current hotel as parameter from template.
关于添加新酒店,您的 addHotel
保持现在的状态.
As for adding a new hotel, your addHotel
stays the way you have it now.
然后转到您的模板,相关部分应如下所示:
Then over to your template, the relevant part should look something like this:
<div formArrayName="HotelData">
<div *ngFor="let hotel of invoiceForm.get('HotelData').controls; let i = index" [formGroupName]="i" >
<!-- form controls here -->
<button (click)="addRoom(hotel.get('RoomData'))">Add Room</button>
<div formArrayName="RoomData">
<div *ngFor="let room of hotel.get('RoomData').controls; let j = index" [formGroupName]="j">
<!-- form controls here -->
</div>
</div>
</div>
</div>
最后,这是一个演示: http://plnkr.co/edit/7tcLcnzALew3oKGenjwK?p=预览
Finally, here's a Demo: http://plnkr.co/edit/7tcLcnzALew3oKGenjwK?p=preview
这篇关于Angular 4使用反应形式在数组内部创建动态formArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!