9

我正在使用 Angular5,并且我有一个字段列表,每个字段都有一个名称和 FormControl。我尝试使用此代码将控件动态添加到组中,但出现错误。

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 不是函数

at FormGroup.registerControl (forms.js:4352)
at FormGroup.addControl (forms.js:4372)
at eval (trade-search.component.ts:142)
4

2 回答 2

8

而是使用new FormControl()语法,它将起作用:

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

于 2018-07-06T12:34:52.900 回答
0

使用 as 运算符进行强制转换时,似乎没有传递或正确设置控制的 formState:

 control: [null, []] as FormControl

但是,向 FormControl 构造函数提供任何值都可以解决问题:

ngOnInit() {
        this.form = new FormGroup({
            'field1': new FormControl(''),
            'field1': new FormControl('')
        }
        console.log(this.form);
    }
于 2018-08-24T06:55:27.360 回答