Reputation: 2132
I want to dynamically add several dishes into this order array. Each dish is a 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?
Upvotes: 0
Views: 61
Reputation: 1566
If I understand what you want correctly, you would likely want a method that returns a formGroup
you want to add to the formArray
.
Making the assumption this is within a component class context.
in .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
get ordersFormArray(): FormArray {
return this.formGroup.get('orders') as FormArray;
}
addOrder() {
this.ordersFromArray.push(this.createOrder())
}
Upvotes: 1