本文介绍了动态创建formGroup时,control.setParent不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Angular5,我有一个字段列表,每个字段都有一个名称和FormControl.我尝试使用此代码将控件动态添加到组中,但出现错误.
I'm using Angular5, and I have a list of fields, each has a name and FormControl. I try to dynamically add the controls to the group, using this code, but I got an error.
const formControlFields = [
{name: 'field1',control: [null, []] as FormControl},
{name: 'field2',control: [null, []] as FormControl}
];
const formGroup: FormGroup = new FormGroup({});
formControlFields.forEach( f => formGroup.addControl(f.name,f.control));
this.form = new FormGroup({groups:formGroup});
这是我得到的错误:
at FormGroup.registerControl (forms.js:4352)
at FormGroup.addControl (forms.js:4372)
at eval (trade-search.component.ts:142)
推荐答案
代替使用new FormControl()
语法,它将起作用:
Instead use the new FormControl()
syntax and it will work:
ngOnInit() {
const formControlFields = [
{ name: 'field1', control: new FormControl(null, []) },
{ name: 'field2', control: new FormControl(null, []) }
];
const formGroup: FormGroup = new FormGroup({});
formControlFields.forEach(f => formGroup.addControl(f.name, f.control));
this.form = new FormGroup({ groups: formGroup });
console.log(this.form);
}
演示: https://stackblitz.com/edit/angular-9vbsgf?file=src%2Fapp%2Fapp.component.ts
这篇关于动态创建formGroup时,control.setParent不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!