Can a structural directive refer to a child component using @ContentChild?

≯℡__Kan透↙ 提交于 2019-12-24 08:18:58

问题


If I have a custom directive ParentDirective and custom component ChildComponent arranged like so:

<div appParent>
  <app-child></app-child>
</div>

...then I can use @ContentChild in the directive to refer to the component:

@ContentChild(ChildComponent) child: ChildComponent;

See this StackBlitz where this is working. (It logs to the console to show that the child member is set).

However, if I change appParent into a structural directive, then the child member is never set.

<div *appParent>
  <app-child></app-child>
</div>

See this StackBlitz.

Is it not possible to use @ContentChild with structural directives?


回答1:


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.

Here is the source code of the createEmbeddedView

  createEmbeddedView(context: any): EmbeddedViewRef<any> {
    return new ViewRef_(Services.createEmbeddedView(
        this._parentView, this._def, this._def.element !.template !, context));
  }

As you can see, it returns a new ViewRef where it injects your context.

More details here.



来源:https://stackoverflow.com/questions/53560347/can-a-structural-directive-refer-to-a-child-component-using-contentchild

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!