Home > Software design >  Angular 3 level nested reactive form inside components
Angular 3 level nested reactive form inside components

Time:11-13

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

Thanks.

CodePudding user response:

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 {}
  • Related