我正在尝试从ng内容中获取元素,这些元素存在于同一个组件中,但我无法获得它们。
组件html
<div>
<ng-content #action></ng-content>
<app-comp2></app-comp2>
</div>组件的.ts
@ContentChildren('action') content:QueryList<ElementRef>;我总是搞不清楚。可能是什么原因?
发布于 2022-11-28 18:24:17
我认为您正在尝试在this.content中获取onInit,在调用ngAfterContentInit钩子之前,ng内容是不可用的。尝试在ngAfterContentInit或ngAfterViewInit中使用ngAfterContentInit
ngAfterContentInit(){
console.log(this.content)
}发布于 2022-11-29 08:23:35
文档提到@ContentChildren中的选择器在内容中选择模板引用。示例: Parent.html
<app-content-component>
<div id="div1" #action>This is the content of component</div>
<div id="div2">This is other content of component</div>
</app-content-component>Component.ts
// this now contains div1 but not div2
@ContentChildren('action') content: QueryList<ElementRef>;不可能用@ContentChildren获取内容中的所有元素。只能对下列情况使用选择器:
支持下列选择器。
实际上,当您用ng-content投影内容时,您实际上可以使用@ViewChild来获取内容,但不能直接在ng-content元素上使用,因为它将被内容替换。但是,您只需将ng-content包装在ng-container中,并向其添加一个模板变量。示例:
Component.html
<div>
<ng-container #myContent>
<ng-content></ng-content>
<ng-container>
<app-comp2></app-comp2>
</div>Component.ts
// this now contains a reference to the ng-container
@ViewChild('myContent') content: ElementRef;https://stackoverflow.com/questions/74603495
复制相似问题