In one of my component's html, we use some <ng-template>
tags.
Inside tags, we would like to define a reference to access the nativeElement
of the div from a @ViewChild
.
The element Ref I want to recover is in tabset directive, within a ng-template of the sub directive p-datatable sub.
Here is our component.html code (we use 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 encounter:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
I tried to move the div with reference on top of tabset, and it works properly. I tried to move the div outside of ng-template and it works too.
How to access an elementRef which is placed inside custom directives, within <ng-template>
?