Template reference variable returns undefined inside ng-template Template reference variable returns undefined inside ng-template angular angular

Template reference variable returns undefined inside ng-template


That is because, the content inside ng-template is not yet rendered.

You should first activate it using ngTemplateOutlet.

Add the following code in your html, it should work

<ng-template #abc>  <div #xyz>      </div></ng-template><ng-container *ngTemplateOutlet="abc"></ng-container>

DEMO


The reason it's happening is because of the ng-template is never rendering on the HTML all by itself.

As per Angular docs:

The ng-template is an Angular element for rendering HTML. It is never displayed directly. In fact, before rendering the view, Angular replaces the and its contents with a comment.

It can be referred to using ngTemplateOutlet or when with *ngIf else or something like that. It doesn't exist on its own:

Update:

<div *ngIf="someConditionCheck;else abc">  content here ...</div><ng-template #abc>  <div #xyz></div></ng-template>

You can find the demo code here.