如何将对象推送到表单控制数组



我有一个formGroup,其中一个formControls是一个数组。

this.newPurchase = fb.group({
supplierName: ["", Validators.required],
supplierNumber: ["", Validators.required],
supplierEmail: ['', Validators.required],
stockitems: [[], Validators.required],
});

正如你所看到的,stockitems被声明为一个数组,我想向它推送一个对象。

这是我尝试过的:

exampleObject = {
name:'foo',
lastName:'fooAgain'
}
this.newPurchase.controls.stockitems.push(this.exampleObject)

对象没有被压入数组,有什么建议吗?

this.newPurchase = fb.group({
supplierName: ["", Validators.required],
supplierNumber: ["", Validators.required],
supplierEmail: ['', Validators.required],
stockitems: this.fb.array([], Validators.required),
});

在你的组件中,放入这个函数:

get stockItemFormControls(): FormArray {
return <FormArray>this.newPurchase.get('stockitems');
}

在需要的地方:

this.stockItemFormControls.push(this.fb.group({name: 'foo', lastName:'fooAgain'}));

this.stockItemFormControls.push(this.fb.group(this.exampleObject));

最新更新