【发布时间】:2021-04-20 23:16:53
【问题描述】:
在一个 Angular 应用程序中,我开发了一个可重用的组件,它负责渲染父组件提供的内容的包装器。包装器提供了多个组件(父组件)所需的一些布局和功能。为了实现这一点,我采用了以下文章中概述的“组件组合”技术,该技术依赖于 NgTemplateOutlet 的使用,以使父组件能够提供在包装器内呈现的内容。
https://blog.bitsrc.io/component-reusability-techniques-with-angular-727a6c603ad2
这种方法在各种情况下都运行良好,但现在我遇到了一种新情况,其中一个父组件需要使用内容查询来获取模板出口内的元素。我在使用 ViewChild 或 ContentChild 装饰器来处理元素方面都没有成功。
以下伪代码概述了我迄今为止尝试采用的基本方法。
可重用元素:
<div class="card">
<ng-container *ngTemplateOutlet="chart"></ng-container>
</div>
...
@ContentChild('chart', {static: false})
chart: TemplateRef<any>;
父组件:
<app-shared-component>
<ng-template #chart>
<div #top10Graph></div>
</ng-template>
</app-shared-component>
...
@ViewChild('top10Graph', { static: false }) private top10GraphContainer: ElementRef;
ngAfterViewInit(): void {
console.log(this.top10GraphContainer); // undefined
}
是否有任何解决方案可以使用内容查询来获取模板出口内的元素,例如我在这里使用的,还是需要其他方法?
最终目标(此处未演示)是使父组件能够在模板出口内呈现数据驱动的图形。
我正在使用 Angular 10。
【问题讨论】:
标签: javascript angular