Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular 3 level nested reactive form inside components

I’m trying to create a 3 level nested form that looks like this: (stackblitz link below)

form = this.formBuilder.group({
    parentControl1: [''],
    parentControl2: [''],
    child1Group: this.formBuilder.group({
      child1Control1: [''],
      child1Control2: [''],
      child2Group: this.formBuilder.group({
        child2Control1: [''],
        child2Control2: [''],
      }),
    }),
  });

There are 3 components: parent, child1 and child2 that are nested. the above form is declared inside the parent. If I omit child2, everything works fine, but with child2 I get this error:

Cannot find control with name: 'child2Group'

Here’s a stackblitz to demonstrate the issue with minimal code: link

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks.

>Solution :

On the third level you should provide FormGroupName as a parent ControlContainer:

child2.component.ts

viewProviders: [
  {
    provide: ControlContainer,
    useExisting: FormGroupName ,
  },
],

Forked Stackblitz

More options

If you don’t know exactly which type of ControlContainer wraps your custom component(for example your controls is inside FormArray directive) then just use common version:

import { SkipSelf } from '@angular/core';
import { ControlContainer} from '@angular/forms';

@Component({
 ...,
 viewProviders: [{
   provide: ControlContainer,
   useFactory: (container: ControlContainer) => container,
   deps: [[new SkipSelf(), ControlContainer]],
 }]
})
export class ChildComponent {}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading