Angular - 如何将多个 FormGroup 插入到一个 FormArray 中?

Angular - How to insert multiple FormGroups to a FormArray?

我试图在加载组件之前将 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: '' }));

问题是,variants.length 值可以是 3、4 等等。如何处理?

// 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: '' }));

FormArray方法只接受一个控件作为参数,因此一次只能添加一个FormGrouphttps://github.com/angular/angular/blob/7.0.2/packages/forms/src/model.ts#L1582-L1593

如果您有多个要添加的 FormGroup 项目,您可以使用 for 循环遍历所有控件并将它们一个一个地推入。

使用这个:

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