Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template reference variable returns undefined inside ng-template

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?

like image 367
Adnan Sheikh Avatar asked Feb 20 '19 09:02

Adnan Sheikh


People also ask

How do I pass a template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

Can we pass data to ng-template?

Similarly if the child <ng-template> is nested inside a parent <ng-template>, even then the child can easily access all the data passed to the parent <ng-template>.

What does template reference variable contain?

A template reference variable is often a reference to a DOM element within a template. It can also refer to a directive (which contains a component), an element, TemplateRef, or a web component.

Can we use ng-container inside ng-template?

ng-container s work just like that, and it also accepts Angular structural directives ( ngIf , ngFor , e.t.c). They are elements that can serve as wrappers but do not add an extra element to the DOM. Here, in the HTML, we can loop through the products array, and display the product's name in a span tag.


1 Answers

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

like image 200
Amit Chigadani Avatar answered Nov 16 '22 03:11

Amit Chigadani