[英]In angular, how to dynamically add different FormGroup into a FormArray?
I want to dynamically add several dishes into this order array.我想在这个订单数组中动态添加几道菜。 Each dish is a FormGroup.
每道菜都是一个 FormGroup。 Dish could be pizza, salad, drink or something else.
菜可以是比萨饼、沙拉、饮料或其他东西。 Before adding anything, the form should look this:
在添加任何内容之前,表单应如下所示:
this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
order: this.fb.array([])
});
After added dishes, form should be something like this:添加菜品后,表格应该是这样的:
this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
order: this.fb.array([
{type:pizza, name:summerPizza, size:8},
{type:salad, name:goodsalad, size:small},
{type:pizza, name:nicePizza, size:11},
{type:drink, name:beer, brand:abc},
])
});
User can add as many items as they want.用户可以根据需要添加任意数量的项目。 So how to do this?
那么如何做到这一点呢?
If I understand what you want correctly, you would likely want a method that returns a formGroup
you want to add to the formArray
.如果我知道你想什么正确的,你可能会想要一个返回的方法
formGroup
要添加到formArray
。
Making the assumption this is within a component class context.假设这是在组件类上下文中。
in .ts:在.ts:
formGroup = this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
order: this.fb.array([])
});
createOrder(): FormGroup {
return this.fb.group({
type: this.fb.control(""),
name: this.fb.control(""),
size: this.fb.control(""),
brand: this.fb.control(""),
});
}
then you'd have a method that would call that createOrder
and add the formGroup
to the formArray
那么你就必须将调用的方法
createOrder
和添加formGroup
到formArray
get ordersFormArray(): FormArray {
return this.formGroup.get('orders') as FormArray;
}
addOrder() {
this.ordersFromArray.push(this.createOrder())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.