Angular 结构指令能否使用@ContentChild引用子组件?
如果我有一个自定义指令Angular 结构指令能否使用@ContentChild引用子组件?,angular,angular-directive,angular-components,Angular,Angular Directive,Angular Components,如果我有一个自定义指令ParentDirective和自定义组件ChildComponent这样排列: <div appParent> <app-child></app-child> </div> 看看这是怎么回事。(它登录到控制台以显示子成员已设置) 但是,如果我将appParent更改为结构指令,则永远不会设置子成员 <div *appParent> <app-child></app-child>
ParentDirective
和自定义组件ChildComponent
这样排列:
<div appParent>
<app-child></app-child>
</div>
看看这是怎么回事。(它登录到控制台以显示子成员已设置)
但是,如果我将appParent更改为结构指令,则永远不会设置子成员
<div *appParent>
<app-child></app-child>
</div>
是否不能将@ContentChild
与结构指令一起使用?我认为您不能,这是由于angular对这两种指令使用的设计。通过TemplateRef
创建指令,并通过ViewContainerRef
的createEmbeddedView
注入指令,将模板生成为dom中的同级,而不是子级。因此,Angular的注射也尊重这一点,这样孩子和造物的地方就看不见对方了。你可以在脑海中画一个额外的图层
是createEmbeddedView
createEmbeddedView(context: any): EmbeddedViewRef<any> {
return new ViewRef_(Services.createEmbeddedView(
this._parentView, this._def, this._def.element !.template !, context));
}
createEmbeddedView(context:any):EmbeddedViewRef我在手机上,所以我无法测试,但它对ViewChild有效吗?@IngoBürk:不。你希望它能吗?据我所知,@ViewChild
允许直接访问组件视图中的组件,而不是其中呈现的内容。我想这可能是因为结构指令本身会分解到模板中,在我看来,子对象更像是视图子对象,而不是内容子对象。不过看来你现在已经有答案了。谢谢你。这并不是我想要的答案,但很高兴知道。
createEmbeddedView(context: any): EmbeddedViewRef<any> {
return new ViewRef_(Services.createEmbeddedView(
this._parentView, this._def, this._def.element !.template !, context));
}