问题描述
如果我有一个自定义指令ParentDirective
和自定义组件ChildComponent
安排如下:
If I have a custom directive ParentDirective
and custom component ChildComponent
arranged like so:
<div appParent>
<app-child></app-child>
</div>
...然后我可以在指令中使用@ContentChild
来引用该组件:
...then I can use @ContentChild
in the directive to refer to the component:
@ContentChild(ChildComponent) child: ChildComponent;
请参见此StackBlitz . (它登录到控制台以显示child
成员已设置).
See this StackBlitz where this is working. (It logs to the console to show that the child
member is set).
但是,如果我将appParent更改为 structural 指令,则永远不会设置child
成员.
However, if I change appParent into a structural directive, then the child
member is never set.
<div *appParent>
<app-child></app-child>
</div>
请参见此StackBlitz .
是否不能在结构指令中使用@ContentChild
?
Is it not possible to use @ContentChild
with structural directives?
推荐答案
我认为您不能这样做,这是由于angular两种指令类型都使用了这种设计.通过TemplateRef
创建指令并通过ViewContainerRef
的createEmbeddedView
注入指令会将模板生成为dom中的同级兄弟,而不是孩子.因此,Angular的注入也要尊重这一点,以使孩子和创建地点无法看到对方.您可以在脑海中画出一个额外的图层.
I think you cannot, and that is due to the design used by angular for both type of directives. Creating a directive via TemplateRef
and injecting it via createEmbeddedView
of ViewContainerRef
generates the template as a sibling in the dom, not as a child. Therefore, Angular's injection also respects this so the child and the place of creation cannot see each other. You can draw it in your mind as an extra added layer there.
这里 是createEmbeddedView
createEmbeddedView(context: any): EmbeddedViewRef<any> {
return new ViewRef_(Services.createEmbeddedView(
this._parentView, this._def, this._def.element !.template !, context));
}
如您所见,它将返回一个新的ViewRef
并在其中注入您的context
.
As you can see, it returns a new ViewRef
where it injects your context
.
这篇关于结构指令可以使用@ContentChild引用子组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!