首页 > 解决方案 > @ContentChildren 和 ng-template 的问题

问题描述

我有一个示例,我试图在 wrapper directive中使用所有指令ContentChildren

具体来说,我已经LookupContainerDirective设置了一个包装元素。然后,在 wrapper 元素中,我有一些模板,并且模板本身也包含LookupdDirective在其中。我正在尝试获取所有LookupdDirective引用LookupContainerDirective

app.component.html

<div appLookupContainer>
  <!-- <div appLookupd></div> -->
  <ng-container *ngTemplateOutlet="myTemp"></ng-container>
</div>  


<ng-template #myTemp>
  <div appLookupd></div>
</ng-template>

查找容器.directive.ts

@ContentChildren(LookupdDirective, { descendants: true })
private _lookupDirectives: QueryList<LookupdDirective>;

ngAfterContentInit() {
  console.log(this._lookupDirectives);
}

我还准备了 stackblitz示例(检查控制台输出)。

我希望控制台输出对的所有引用,LookupdDirective但它显示没有(_results: Array[0])。如果我不使用模板而是使用常规元素,则会找到引用 ( _results: Array[1])。

标签: angulartypescript

解决方案


正在对此进行讨论

一个建议的解决方法是这样;

<div appLookupContainer>
    <ng-container *ngTemplateOutlet="myTemp"></ng-container>

    <ng-template #myTemp>
        <div appLookupd></div>
    </ng-template>
</div>

正如这里所解释的

在 Angular 内容投影和查询中,它表示“在模板中编写的内容”,而不是您似乎期望的“在 DOM 中可见的内容”。


推荐阅读