I would like to access an element with ViewChild that is rendered with innerHtml, but in the lifecycle hook AfterViewInit, logging the element return undefined.
Below is the code used:
import { Component, ViewChild, ChangeDetectorRef, AfterViewInit } from '@angular/core';
@Component({
template: `<p [innerHTML]="'<ng-template #innerHtmlNgTemplate></ng-template>' | safeHtml"></p>`
})
export class AppComponent {
@ViewChild('innerHtmlNgTemplate') public innerHtmlNgTemplate;
ngAfterViewInit() {
console.log(this.innerHtmlNgTemplate); // undefined
}
}
The question is how can I access the <ng-template></ng-template>
with ViewChild or in another way?
Cheers
EDIT:
Here is a stackblitz showing the issue. https://stackblitz.com/edit/angular-k1xeh6?file=src%2Fapp%2Fapp.component.ts
EDIT2:
In the stackblitz I sanitized the html, if this isn't done the ids are removed.
The answer to the question is you should not do this. Angular is not designed to work this way.
This is the partial response from the angular issue thread.
When you insert HTML string through innerHTML, such string is not processed by Angular. As such you can't expect any Angular syntax / functionality (including queries) to work - simply put Angular has no chance of processing static HTML inserted into innerHTML. In this respect the observed behaviour "works as designed".
I'm not sure what your exact, functional use-case is but the scenario you've exposed is not something that Angular supports today and quite honestly, this is not how it was designed in the first place.
Github issue: https://github.com/angular/angular/issues/35874