结构指令可以使用@ContentChild引用子组件吗? [英] Can a structural directive refer to a child component using @ContentChild?

查看:134
本文介绍了结构指令可以使用@ContentChild引用子组件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个自定义指令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引用子组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆