Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

control.setParent is not a function when dymanically creating formGroup

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)
like image 606
matchifang Avatar asked Jul 06 '18 11:07

matchifang


1 Answers

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

like image 133
AT82 Avatar answered Nov 13 '22 15:11

AT82