0

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?

1 Answer 1

1

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())
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.