14

Already tried this and this solution but nothing worked.

I am using Angular 7 and trying to get a reference variable which I've placed inside the ng-template tag. But it always returns undefined

test-component.html

<ng-template #abc>
  <div #xyz>    
  </div>
</ng-template>

test-component.ts

@ViewChild('abc') abc: ElementRef; //---> works fine
@ViewChild('xyz') xyz: ElementRef; //---> undefined

test-component.ts

ngAfterViewInit(){
  console.log(this.xyz); //---> undefined  
}

I've tried printing it in all the life cycle hooks of angular but it always returns undefined. But when I try putting it in out side of ng-template it works perfectly.

Is there any way around?

Adnan Sheikh
  • 760
  • 3
  • 13
  • 27

2 Answers2

6

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

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
  • Thank you @Amit, It works. But I am using [NgbPopOver] (https://ng-bootstrap.github.io/#/components/popover/examples#tplcontent) for a chat module. It messes with the design when I put ng-container at the end. Any idea? – Adnan Sheikh Feb 20 '19 at 10:01
  • It seems it just behaves like a simple div when we put ng-container below the ng-template. Am I right? – Adnan Sheikh Feb 20 '19 at 10:16
  • https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/ – Amit Chigadani Feb 20 '19 at 10:20
4

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.

Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104