Update:
Indeed there is an easier way:
import { FormsModule, ControlContainer, NgForm, NgModel } from '@angular/forms';
@Component({
...
viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class ChildComponent {}
See also
Previous version:
I would say it's possible. For example you could add the following code to 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
Angular DI system gives us the opportunity to get reference to parent NgForm
instance because angular dependency resolution algorithm starts with current node and goes up through tree of elements. In my example we can imagine the follwing tree
@NgModule providers
|
my-app
|
form
/ | \
input[text] input[text] child-component
So when we are requiring NgForm
token angular will search it in the next order
child-component
||
\/
form
||
\/
my-app
||
\/
@NgModule
On form element NgForm
directive is placed so when can get it. Also we can get any token that was declared on NgForm
directive within providers
array. And this rule applies to any node.
See also Angular 2 - How does ng-bootstrap provide the NgbRadioGroup and NgbButtonLabel to their NgbRadio directive?
Then i just added child NgModel
directives manually to NgForm
so they should work together.