向角formGroup
添加新对象属性的正确方法是什么?
我已经设置好了:
ngOnInit() {
this.form = this.fb.group({
// store is the formGroupname
store: this.fb.group({
// branch and code are formControlName
branch: ['asdf', Validators.required],
code: ['asdf', Validators.required],
}),
selector: this.createStock({}),
stock: this.fb.array([
this.createStock({product_id: '1', quantity: 20}),
this.createStock({product_id: '2', quantity: 30}),
this.createStock({product_id: '3', quantity: 40}),
]),
});
}
在store属性中,如果要单击复选框,我想添加。在阅读了有角度的文档后,我得到了正在解决的解决方案,但是在vscode上给了我红线。我想知道这是正确的方法吗?
解决方案:
onSubmitForm() {
// adding dynamic formgroup
if(this.form.get('checkBoxStore').value)
this.form.get('store').addControl(
'foo',
this.fb.group({
testingAdd: this.form.get('test').value,
})
);
}
图片:
答案 0 :(得分:4)
由于FormGroup
扩展了AbstractControl
,因此您收到该错误,当您使用get()
时,它是AbstractControl
的一种,因此要解决此问题,您需要将其强制转换为FormGroup
(this.form.get('store') as FormGroup).addControl(...)
请参见stackblitz
答案 1 :(得分:2)
您可以将abstractformcontrol转换为formgroup,并将其可变实例存储到变量中,然后执行addcontrol操作,如下所示:
const store: FormGroup = this.form.get('store') as FormGroup;
store.addControl(
'foo',
this.fb.group({
testingAdd: this.form.get('test').value,
})
);