【问题标题】:Angular > How to use a content query to get an element inside an template outletAngular > 如何使用内容查询来获取模板出口内的元素
【发布时间】:2021-04-20 23:16:53
【问题描述】:

在一个 Angular 应用程序中,我开发了一个可重用的组件,它负责渲染父组件提供的内容的包装器。包装器提供了多个组件(父组件)所需的一些布局和功能。为了实现这一点,我采用了以下文章中概述的“组件组合”技术,该技术依赖于 NgTemplateOutlet 的使用,以使父组件能够提供在包装器内呈现的内容。

https://blog.bitsrc.io/component-reusability-techniques-with-angular-727a6c603ad2

这种方法在各种情况下都运行良好,但现在我遇到了一种新情况,其中一个父组件需要使用内容查询来获取模板出口内的元素。我在使用 ViewChildContentChild 装饰器来处理元素方面都没有成功。

以下伪代码概述了我迄今为止尝试采用的基本方法。

可重用元素:

<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


    【解决方案1】:

    我认为您未定义是因为尚未渲染使用 ng-template
    此代码可以为您工作

    <app-shared-component>
        <ng-template #chart>
            <div #top10Graph></div>
        </ng-template>
        <ng-container *ngTemplateOutlet="chart"></ng-container>
    </app-shared-component>
    

    希望有用

    【讨论】:

    • 感谢您的意见!如果我正确理解了您的建议,则需要将模板出口(“图表”)移动到父组件中,这在我的特定情况下不起作用,因为它需要由共享/可重用组件呈现。对于我的特殊需求,我决定最好的解决方案是创建一个属性指令来呈现图形,在这种情况下,我的父组件根本不再需要元素句柄。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 2011-11-17
    • 2011-05-06
    相关资源
    最近更新 更多