结构指令可以使用@ContentChild 引用子组件吗?

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

如果我有自定义指令 ParentDirective 和自定义组件 ChildComponent 排列如下:

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

...然后我可以在指令中使用 @ContentChild 来引用组件:

@ContentChild(ChildComponent) child: ChildComponent;

请参阅 this StackBlitz 这是有效的地方。 (它记录到控制台以显示 child 成员已设置)。

但是,如果我将 appParent 更改为 structural 指令,则永远不会设置 child 成员。

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

参见 this StackBlitz

结构指令不能使用@ContentChild吗?

我认为你不能,这是由于 angular 对这两种类型的指令所使用的设计。通过 TemplateRef 创建指令并通过 ViewContainerRefcreateEmbeddedView 注入它 生成模板作为 dom 中的同级,而不是 child。因此,Angular的注入也遵循这一点,所以child和创建的地方不能相互看到。你可以把它画在你的脑海里作为一个额外的附加层。

HerecreateEmbeddedView

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

如您所见,它 returns 一个新的 ViewRef 注入您的 context

More details here.