本文介绍了在组件中获取动态模板的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是模板:
<button (click)="loadTemplate()">Load Template</button>
<ng-template #tmpl let-name>
<h2>hello</h2>
<h2>{{name}}</h2>
</ng-template>
以下是组件:
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)
}
}
当我记录"viewRef.rootNodes"时,我可以看到静态文本"hello",但是缺少通过隐式上下文传递的动态文本"angular".
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-上下文
Stackblitz - https://stackblitz.com/edit/angular-dynamic-template-context
这里有什么我想念的吗?
Is there anything I am missing out here?
推荐答案
您错过了以下事实:动态数据需要更改检测周期才能发生:
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
这篇关于在组件中获取动态模板的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!