Reputation: 1494
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?
Upvotes: 2
Views: 627
Reputation: 214007
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)
Upvotes: 2