动态创建 formGroup 时 control.setParent 不是函数 [英] control.setParent is not a function when dymanically creating formGroup

查看:20
本文介绍了动态创建 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});

这是我得到的错误:

错误类型错误:control.setParent 不是函数

ERROR TypeError: control.setParent is not a function

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/编辑/angular-9vbsgf?file=src%2Fapp%2Fapp.component.ts

这篇关于动态创建 formGroup 时 control.setParent 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆