假设我有一个如下组件:
<app-my-typical-form>
<app-child-in-content></app-child-in-content>
</app-my-typical-form>
哪里my-typical-form.component.html
是:
<form #f="ngForm">
<ng-content></ng-content>
</form>
<hr>
<h3>Here is my form from the parent:</h3>
{{f|json}}
和child-in-content.component.html
和child-in-content.component.ts
如下:
<h2>
My Form from the projected content is:
</h2>
<br>
{{myForm|json}}
@Component({
selector: 'app-child-in-content',
templateUrl: './child-in-content.component.html',
})
export class ChildInContentComponent {
constructor(@Optional() public myForm: NgForm) { }
}
正如您在StackBlitz中看到的那样,myForm
inapp-child-in-content
为空。但是,我的理解是,既然child-in-content
是(种)孩子,NgForm
我可以通过 DI 拥有它。由于内容投影,这显然不起作用。
那么,有没有办法在app-child-in-content
组件中获取 NgForm(编辑:之前ViewInit
)?