共计 1503 个字符,预计需要花费 4 分钟才能阅读完成。
本文探讨问题的代码,位于 Github:https://github.com/wangzixi-d…
问题形容
我的 Component 代码如下图所示:
- 应用依赖注入,引入
ViewContainerRef
,从而能够应用其createEmbeddedView
办法,在运行时动态创建实例。 - 应用
@ViewChild
,取得该 Component HTML 源代码里定义的 id 为 tpl 的模板实例,类型为TemplateRef
。 - Component 的 HTML 源代码:
<ng-template tpl>
<div>
Hello, ng-template!
</div>
</ng-template>
然而启动利用,呈现运行时谬误:
ERROR TypeError: Cannot read properties of undefined (reading ‘createEmbeddedView’)
at ViewContainerRef.createEmbeddedView (core.js:10190:45)
at NgTemplateComponent.push.8YnP.NgTemplateComponent.ngAfterViewInit (ng-template.component.ts:20:20)
at callHook (core.js:3281:18)
at callHooks (core.js:3251:17)
at executeInitAndCheckHooks (core.js:3203:9)
at refreshView (core.js:7451:21)
at renderComponentOrTemplate (core.js:7494:9)
at tickRootContext (core.js:8701:9)
at detectChangesInRootView (core.js:8726:5)
at RootViewRef.detectChanges (core.js:9991:9)
问题剖析
上述调用上下文里,有一个栈帧是咱们应用程序的代码:
ngAfterViewInit (ng-template.component.ts:20:20)
在其办法内设置断点, 发现运行时,this.tplRef 为空。
在值为 undefined 的变量上调用 createEmbeddedView
导致的这个谬误。
问题转化为:this.tplRef
的赋值逻辑是怎么的?
在 ngOnInit 时,这个属性还是 undefined 状态:
咱们把鼠标 hover 在 @ViewChild
上查看其阐明:
变更检测器会在视图的 DOM 中查找能匹配上该选择器的第一个元素或指令。如果视图的 DOM 产生了变动,呈现了匹配该选择器的新的子节点,该属性就会被更新。
发现输出参数是一个选择器,本例我传入的选择器是 id 选择器:tpl
依据 Angular 官网文档,这意味着我的 HTML 模板文件里,tpl 之前应该用 #
润饰:
解决方案
在 tpl 前增加 #
:
总结
如果咱们想进一步察看 view query 是如何依据传入的选择器 tpl
,去 dom tree 里查找的节点,能够增加如下代码,即 @ViewChild 和 set 函数搭配应用的状况。
@ViewChild('tpl')
set thisNamedoesnotMatter(v:TemplateRef<any>){console.log('Jerry');
this.tplRef = v;
}
通过调试,发现 view query 的执行过程不会显示在 Chrome 开发者工具里,而仅仅显示一个 dummy 的 XXX(Component 名称)_Query 的调用上下文。
set 函数里的输出参数 v 代表的就是 id 为 tpl 的 Template 实例。