How to get innerHTML that contain ng-template?

114 Views Asked by At

This is my app.component.html:

<div #content>
    Hello world
    <ng-template>
        inside template
    </ng-template>
</div>

And this is my app.component.ts

@ViewChild('content', { read: ElementRef }) refContent: ElementRef;

...

console.log(this.refContent.nativeElement);

And this is the output:

<div _ngcontent-kst-c255=""> 
    Hello world 
    <!--container-->
</div>

How to get the console to print like this?

<div _ngcontent-kst-c255=""> 
    Hello world 
    inside template
</div>
2

There are 2 best solutions below

0
VHanded On

I put a timeout of 1000 ms before calling

console.log(this.refContent.nativeElement);

And it works now. The renderer just need some time to render it.

1
Aniket Raj On

Use Angular life cycle hook

ngAfterViewInit : A callback method that is invoked immediately after Angular has completed initialization of a component's view. It is invoked only once when the view is instantiated.

ngAfterViewInit() {
//here put the ViewChild elements Reference variables
console.log(this.refContent.nativeElement);
}