This allows you to split a template-driven form on components.
Create formProvider
directive to proxy ngModel
injector from parent to child:
import { Directive, SkipSelf, forwardRef } from '@angular/core';
import { ControlContainer, Form } from '@angular/forms';
@Directive({
selector: '[formProvider]',
providers: [
{
provide: ControlContainer,
useFactory: (parent) => parent,
deps: [[new SkipSelf(), ControlContainer]],
}
]
})
export class FormProviderDirective {
}
Use it in a child component:
<ng-container formProvider>
<input name="inChild" [(ngModel)]="form.inChild">
</ng-container>
- Parent component should have
<form>
element. Child components should be inside of that element. - Each
ngModel
should have uniquename
(can be an issue in cycles). - There is alternative method with
viewProviders
instead a directive: https://medium.com/@a.yurich.zuev/angular-nested-template-driven-form-4a3de2042475