我尝试使用嵌套模板驱动表单,但我PostEditorComponent
textarea中的ngModel无法找到ngForm
中的ModalFormComponent
。这是我目前的设置:
Component({
selector: 'modal-form',
template: `
<div class="modal-window">
<div class="modal-body">
<form #form="ngForm">
<ng-content></ng-content>
</form>
</div>
</div>
`
})
export class ModalFormComponent {
}
@Component({
selector: 'post-editor',
template: `
<textarea [(ngModel)]="postContent" required name="postContent"></textarea>
`
})
export class PostEditorComponent {
public postContent: string;
}
@Component({
selector: 'write-post',
template: `
<modal-form>
<label>
Post type: <input type="text" [(ngModel)]="postTitle" name="postTitle"/>
</label>
<post-editor></post-editor>
</modal-form>
`
})
export class WritePostComponent {
public postTitle: string;
}
如果我尝试在viewProviders: [{provide: ControlContainer, useExisting: NgForm}]
Angular throws中PostEditorComponent
使用NullInjectorError: No provider for NgForm!
使用@ViewChildren(NgModel)
和ngForm.addControl(model)
进行手动关联可能是一种解决方案,但由于我必须管理引用,处理AfterViewInit
,OnDestroy
等,因此容易出错。< / p>
关于如何将表单实例注入PostEditorComponent
视图的任何想法?