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?
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 .
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>.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With