Recent Update:
It turns out there is a simpler solution:
import { FormsModule, ControlContainer, NgForm, NgModel } from '@angular/forms';
@Component({
...
viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class ChildComponent {}
Additional Resources:
- Angular2 nested template driven form
Previous Version Details:
It seems very much possible. For instance, you could integrate the following code within your
child.component.ts
import { NgForm, NgModel } from '@angular/forms';
@Component({
selector: 'child-component',
template: `
<input type="text" name="thirdControl" [(ngModel)]="thirdControl" />
<input type="text" name="fourthControl" [(ngModel)]="fourthControl" />
`
})
export class ChildComponent {
@ViewChildren(NgModel) ngModels: QueryList<NgModel>;
constructor(@Optional() private ngForm: NgForm) {}
ngAfterViewInit() {
if (this.ngForm) {
this.ngModels.forEach(model => this.ngForm.addControl(model));
}
}
}
Plunker Example
The Angular DI system grants us the ability to access the parent NgForm
instance because the angular dependency resolution algorithm begins with the current node and traverses upwards through the element hierarchy. In my example, we can visualize the following hierarchy
@NgModule providers
|
my-app
|
form
/ | \
input[text] input[text] child-component
Therefore, when we request the NgForm
token, Angular will search for it in the following sequence
child-component
||
\/
form
||
\/
my-app
||
\/
@NgModule
The NgForm
directive is positioned on the form element, allowing us to access it. We can also access any token declared within the providers
array of the NgForm
directive. This principle applies to any node in the hierarchy.
For further information, check out Angular 2 - How does ng-bootstrap provide the NgbRadioGroup and NgbButtonLabel to their NgbRadio directive?
Subsequently, I manually included child NgModel
directives within NgForm
to ensure their seamless operation together.