我正在使用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});

这是我得到的错误:

最佳答案

而是使用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

关于angular - 动态创建formGroup时control.setParent不是函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51209125/

10-12 00:25