Andrew Kirk
Andrew Kirk

Reputation: 1869

Angular > How to use a content query to get an element inside an template outlet

In an Angular app, I've developed a reusable component whose responsibility to take care of rendering a wrapper around content provided by the parent component. The wrapper provides some layout and functionality that is required by multiple components (the parents). To accomplish this, I've adopted the "Component Composition" technique outlined in the following article which relies on the use of NgTemplateOutlet to enable the parent component to provide the content rendered inside the wrapper.

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

This approach has been working well in a variety of situations but now I've come across a new situation where one of the parent components needs to use a content query to get an element inside the template outlet. I've been unsuccessful in using either the ViewChild or ContentChild decorators to get a handle on the element.

The following pseudo code outlines the basic approach I've attempted to take to date.

Reusable Element:

<div class="card">
    <ng-container *ngTemplateOutlet="chart"></ng-container>
</div>
...
@ContentChild('chart', {static: false})
  chart: TemplateRef<any>;

Parent Component:

<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
}

Is there any solution for using a content query for obtaining an element inside a template outlet such as I'm using here, or is another approach required?

The end goal (not demonstrated here) is to enable the parent component to render a data driven graph inside the template outlet.

I'm using Angular 10.

Upvotes: 0

Views: 982

Answers (1)

A.khalifa
A.khalifa

Reputation: 2496

I think you get undefined because using ng-template is not yet rendered.
This code can work for you

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

Hope useful

Upvotes: 1

Related Questions