error TS2339 when trying to add child FormGroup in Angular

118 views Asked by At

I'm using Angular8 and trying to add a child FormGroup to a form using addControl:

    this.testForm = new FormGroup({
        id: new FormControl(0),
        people: new FormGroup({
        }),
    });
    this.testForm.controls['people'].addControl('numbers', new FormGroup({
        number: new FormControl('1234')
    }));

This gives me compiler error: error TS2339: Property 'addControl' does not exist on type 'AbstractControl'.

Really stuck with this, so all help much appreaciated!

2

There are 2 answers

0
Никита Середа On

FormGroup extended class from AbstractControl has addControl and this method is not part of parent class AbstractControl. So when you use the method get, the returned element is an AbstractControl, not FormGroup, so you should ensure the returned element is a FormGroup and cast it properly to use addControl method.

With this in mind, you can use addControl, adding in your code something like this:

abstractControl : AbstractControl = this.formGroup.get(tab.id);
if(abstractControl instanceof FormGroup){
    (<FormGroup>abstractControl).addControl(segment.id, this.formBuilder.group({}));
}
0
mbojko On

Type assertion should be enough: instead of

    this.testForm.controls['people'].addControl( // ...

do

    (this.testForm.controls['people'] as FormGroup).addControl( //...