Ansuman
Ansuman

Reputation: 1494

Getting content of dynamic templates in component

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

Answers (1)

yurzui
yurzui

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)

Forked Stackblitz

Upvotes: 2

Related Questions