Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度-如何将多个FormGroup插入到FormArray?_Javascript_Angular_Typescript_Angular Reactive Forms - Fatal编程技术网

Javascript 角度-如何将多个FormGroup插入到FormArray?

Javascript 角度-如何将多个FormGroup插入到FormArray?,javascript,angular,typescript,angular-reactive-forms,Javascript,Angular,Typescript,Angular Reactive Forms,我试图在加载组件之前将FormGroups插入FormArray。这是我的表格组: /*constructor (private fb: FormBuilder) {}*/ this.productGroup = this.fb.group({ name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])], variants: this.fb.array([ this.fb.group

我试图在加载组件之前将FormGroups插入FormArray。这是我的表格组:

/*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: ''
    })
  ]),
});
这就是我在
variants
FormArray中插入FormGroup的方式:

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

FormArray
方法只接受一个控件作为参数,因此一次只能添加一个
FormGroup

如果要添加多个
FormGroup
项,则可以使用for循环迭代所有控件,并将它们逐个推入

使用以下命令:

const dataBaseVariantsLength = objectFromDataBaseLength;
for (let i = 0; i < dataBaseVariantsLength; i++) {
  variants.push(this.fb.group({ _id: '', type: '', options: '' }));
}
const dataBaseVariantsLength=objectFromDataBaseLength;
for(设i=0;i
我回答了你的问题,但实际上我在想,你想要实现什么?也许我错过了你要找的东西?@jburtondev我正在从数据库推送整个对象,所以
variants
length是可变的谢谢。我理解你的意思,它会导致无限n+1循环。所以变量的长度应该保持不变,对吗?您只想在表单数组中添加尽可能多的新组吗?是的,我需要有与变体相同数量的表单组,这样就可以修补数据库中的值了。很酷,写下答案就完美了。
const dataBaseVariantsLength = objectFromDataBaseLength;
for (let i = 0; i < dataBaseVariantsLength; i++) {
  variants.push(this.fb.group({ _id: '', type: '', options: '' }));
}