Angular: Multiple nested FormGroups in Component
Asked Answered
B

1

6

I'm trying to nest several FormGroups, which works very well if I do not want to outsource the template to own components.

Here is an example, that works

Template

<form [formGroup]="baseForm">
  <div formGroupName="nestedForm1">
    <div formGroupName="nestedForm2">
      <input formControlName="nestedControl">
    </div>
  </div>
</form>

Typescript

this.baseForm = this.formBuilder.group({
  nestedForm1: this.formBuilder.group({
    nestedForm2: this.formBuilder.group({
      nestedControl: ["Default Value"]
    })
  })
});

If I try to outsource the "nestedForm1" and "nestedForm2" into a separate component, it does not work anymore from the second level.

An example can be found at the following link. There you can try both ways by commenting out the respective code parts in the "app.component.html"

https://stackblitz.com/edit/angular-gnpw24?file=src%2Fapp%2Fapp.component.html

Backstroke answered 29/11, 2018 at 18:42 Comment(0)
S
4

That's because ControlContainer provider can be registered on any of these directives:

Template driven directives

  • NgForm
  • NgModelGroup,

Reactive directives

  • FormGroupDirective
  • FormGroupName
  • FormArrayName

but you expect that it will be always FormGroupDirective while in the second component parent ControlContainer is FormGroupName.

I would use common solution which will work regardless type of parent ControlContainer:

viewProviders: [{
  provide: ControlContainer,
  useFactory: (container: ControlContainer) => container,
  deps: [[new SkipSelf(), ControlContainer]],
}]

Forked Stackblitz

Smithereens answered 29/11, 2018 at 18:54 Comment(5)
This works like a charm, thank you for this quick answer :-DBackstroke
How to get it working when each nested form group is defined in component?Phocis
@Phocis Can you provide an example on stackblitz?Smithereens
@Smithereens stackblitz.com/edit/angular-bwiq87. as you can see nestedForm1 is nullPhocis
@Phocis Option 1 stackblitz.com/edit/angular-c7znw8?file=src/app/… Option 2 stackblitz.com/edit/angular-tbkqg2?file=src/app/…Smithereens

© 2022 - 2024 — McMap. All rights reserved.