3

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: '' }));
7
  • I answered your question, but I am actually thinking, what do you want to achieve? Perhaps I have missed what you are looking for? Commented Nov 5, 2018 at 22:34
  • @jburtondev Im pushing the whole object from database, so variants length is variable Commented Nov 5, 2018 at 22:44
  • Thanks. I understand what you mean, it will cause an infinite n+1 loop. So the variants length should stay the same right? You just want to add as many new groups as there are arrays into your Form Array? Commented Nov 5, 2018 at 22:49
  • Yes, I need to have the same amount of form groups as variants, so it will be ready for patching the values from database. Commented Nov 5, 2018 at 22:53
  • Cool, perfect just writing the answer. Commented Nov 5, 2018 at 22:55

1 Answer 1

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.