Access elementRef inside ng-template contained in directive

In one of my html components we are using tags <ng-template>

.

Inside the tags, we would like to define a link to access the nativeElement

div from a @ViewChild

.

The Ref element I want to restore is in the tabset directive, within the ng template of the p-datatable sub-directive.

Here is our component.html code (we are using primeNG and ngx-bootstrap modules and tabs / datatable directives):

<tabset #staticTabs>
    <tab>
        <ng-template tabHeading>
            <span class="hidden-sm-down">
                Tab Header Text
            </span>
        </ng-template>          
        <p-dataTable [value]="data">
            <p-column field="id" header="Id"></p-column>
            <p-column field="context" header="Context">
                <ng-template let-context="rowData" pTemplate="body">
                    <div class="container" #iWantThisElementNative></div>
                </ng-template>
            </p-column>
        </p-dataTable>
    </tab>
</tabset>

      

And our component .ts:

export class AppComponent implements OnInit, AfterViewInit {
  @ViewChild('iWantThisElementNative') iWantThisElementNative;

  ...

  ngAfterViewInit() {
    console.log(this.iWantThisElementNative.nativeElement);
  }
}

      

And the error we are facing:

ERROR: Uncleanness (in promise): TypeError: Cannot read property 'nativeElement' from undefined

I tried to move the div with the link to the top of the tabset and it works correctly. I tried moving the div outside the ng template and it works too.

How do I access the Ref element that is placed inside custom directives within <ng-template>

?

+3


source to share





All Articles