Getting content of dynamic templates in component

大城市里の小女人 提交于 2021-02-11 05:16:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!