8

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

BlackHoleGalaxy
  • 9,160
  • 17
  • 59
  • 103
  • `ng-template` element is not rendered in the DOM (it's rendered as a comment usually), its contents is compiled and can be accessed with `templateRef`, probably that's what `p-column` component is doing - injects templateRef and works with it – Max Koretskyi Jun 12 '17 at 17:36
  • Can you please let us know what your end goal is, after getting a reference to the element? If we know that, maybe we can suggest alternatives. – CodeWarrior Jun 12 '17 at 18:20
  • 1
    Try to move the console log under setTimeout. Like setTimeout(()=>console.log(this.iWantThisElementNative.nativeElement)); – Julia Passynkova Jun 12 '17 at 18:53
  • Hi @CodeWarrior in fact the `this.iWantThisElementNative.nativeElement` will be used to manipulate a canvas in the div and draw something in it. So i need to access it to be able to get the context(2d) (for example then use `this.iWantThisElementNative.nativ‌​eElement.getContext('2d').fillText(text, x, y);` – BlackHoleGalaxy Jun 12 '17 at 18:55
  • Hey, could you update your example or post a solution. I came up with the same error.. – muuvmuuv Oct 20 '17 at 17:24

0 Answers0