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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

This works like a charm, thank you for this quick answer :-D
How to get it working when each nested form group is defined in component?
@maxlego Can you provide an example on stackblitz?
@yurzui stackblitz.com/edit/angular-bwiq87. as you can see nestedForm1 is null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.