3

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

4

1 回答 1

2

这是因为ControlContainer提供者可以在以下任何指令上注册:

模板驱动指令

  • 表格
  • NgModelGroup,

反应式指令

  • 表单组指令
  • 表单组名
  • 表单数组名

但是您希望它总是FormGroupDirective在第二个组件中时 parent ControlContaineris FormGroupName

我会使用通用解决方案,无论父母类型如何ControlContainer

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

分叉的 Stackblitz

于 2018-11-29T18:54:37.307 回答