James
James

Reputation: 1219

Angular - How to insert multiple FormGroups to a FormArray?

I'm trying to insert FormGroups into a FormArray before a component is loaded. This is my FormGroup:

/*constructor (private fb: FormBuilder) {}*/
this.productGroup = this.fb.group({
 name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])],
  variants: this.fb.array([
    this.fb.group({
      _id: '',
      type: '',
      options: ''
    })
  ]),
});

And this is how I'm inserting a FormGroup inside variants FormArray:

const variants = <FormArray>this.productGroup.controls.variants;
variants.push(this.fb.group({ _id: '', type: '', options: '' }));

Problem is, variants.length value can be 3, 4 and so on. How to deal with it?

// variants.lenght == 2
variants.push(this.fb.group({ _id: '', type: '', options: '' }));
variants.push(this.fb.group({ _id: '', type: '', options: '' }));

// variants.lenght == 3
variants.push(this.fb.group({ _id: '', type: '', options: '' }));
variants.push(this.fb.group({ _id: '', type: '', options: '' }));
variants.push(this.fb.group({ _id: '', type: '', options: '' }));

Upvotes: 3

Views: 9713

Answers (1)

jburtondev
jburtondev

Reputation: 3253

The FormArray method only accepts one control as an argument, therefore you can only add one FormGroup at a time: https://github.com/angular/angular/blob/7.0.2/packages/forms/src/model.ts#L1582-L1593

You can use a for loop to iterate over all of the controls and push them in one by one, if you have multiple FormGroup items that you would like to add.

Use this:

const dataBaseVariantsLength = objectFromDataBaseLength;
for (let i = 0; i < dataBaseVariantsLength; i++) {
  variants.push(this.fb.group({ _id: '', type: '', options: '' }));
}

Upvotes: 4

Related Questions