control.setParent is not a function when dymanically creating formGroup

独自空忆成欢 提交于 2019-12-10 15:48:24

问题


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});

This is the error I get:

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)

回答1:


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);
} 

Demo: https://stackblitz.com/edit/angular-9vbsgf?file=src%2Fapp%2Fapp.component.ts




回答2:


Seems like formState for control is not passed or correctly set when using casting with as operator:

 control: [null, []] as FormControl

However providing any value to FormControl constructor will solve the issue:

ngOnInit() {
        this.form = new FormGroup({
            'field1': new FormControl(''),
            'field1': new FormControl('')
        }
        console.log(this.form);
    }


来源:https://stackoverflow.com/questions/51209125/control-setparent-is-not-a-function-when-dymanically-creating-formgroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!