简体   繁体   English

@ContentChildren和ng-template有问题

[英]A problem with @ContentChildren and ng-template

I have an example where I am trying to get all directives using ContentChildren in wrapper directive . 我在那里,我试图让使用所有指令的例子ContentChildren在包装指令

Specifically, I have LookupContainerDirective set on a wrapper element. 具体来说,我在包装元素上设置了LookupContainerDirective Then, inside the wrapper element, I am have some template and the template itself has LookupdDirective in it. 然后,在wrapper元素内部,我有一些模板,并且模板本身中包含LookupdDirective I am trying to get all LookupdDirective references in LookupContainerDirective . 我正在尝试在LookupContainerDirective获取所有LookupdDirective引用。

app.component.html app.component.html

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


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

lookup-container.directive.ts 查找-container.directive.ts

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

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

I also prepared stackblitz example (check console output). 我还准备了stackblitz示例(检查控制台输出)。

I expect that the console outputs all references to the LookupdDirective but instead it shows that there is none ( _results: Array[0] ). 我希望控制台输出对LookupdDirective所有引用,但是它将显示没有_results: Array[0]_results: Array[0] )。 If I don't use the template but regular element then the references are found ( _results: Array[1] ). 如果我不使用模板而是常规元素,则可以找到引用( _results: Array[1] )。

there is an ongoing discussion about this. 对此正在进行讨论

and one suggessted workaround is this; 建议的解决方法是此方法;

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

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

as explained here 这里解释

In Angular content projection and queries it means "content as it was written in a template" and not "content as visible in the DOM" as you seem to expect. 在Angular内容投影和查询中,它的意思是“如模板中所写的内容”,而不是您所期望的“在DOM中可见的内容”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM