动态创建 @ViewChild 导致运行时错误的原因分析
本文讨论问题的代码,位于 Github:https://github.com/wangzixi-diablo/ngDynamic
问题描述
我的 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 实例。