问题
Here is the template:
<button (click)="loadTemplate()">Load Template</button>
<ng-template #tmpl let-name>
<h2>hello</h2>
<h2>{{name}}</h2>
</ng-template>
Here is the component:
export class AppComponent {
@ViewChild("tmpl", { read: TemplateRef, static: false }) tmpl: TemplateRef<any>;
loadTemplate() {
const viewRef = this.tmpl.createEmbeddedView({ $implicit: "angular" })
alert('content for static h2 element: ' + viewRef.rootNodes[0].textContent)
alert('content for dynamic h2 element: ' + viewRef.rootNodes[1].textContent)
}
}
When I am logging 'viewRef.rootNodes', I could see the static text 'hello' but the dynamic text 'angular' which I am passing through implicit context is missing.
Stackblitz - https://stackblitz.com/edit/angular-dynamic-template-context
Is there anything I am missing out here?
回答1:
You missed the fact that dynamic data requires change detection cycle to happen:
const viewRef = this.tmpl.createEmbeddedView({ $implicit: "angular" });
viewRef.detectChanges(); // try adding this
alert('content for static h2 element: ' + viewRef.rootNodes[0].textContent)
alert('content for dynamic h2 element: ' + viewRef.rootNodes[1].textContent)
Forked Stackblitz
来源:https://stackoverflow.com/questions/61970568/getting-content-of-dynamic-templates-in-component