共计 1560 个字符,预计需要花费 4 分钟才能阅读完成。
问题形容
本文波及到的代码地位:https://github.com/wangzixi-d…
ng-container
和 ngTemplateOutlet
的配合应用。
<ng-container [ngTemplateOutlet]="content.templateRef"></ng-container>
这里须要承受一个类型为 TemplateRef
的输出:
content.templateRef 在哪里赋的值?
应用了 ContentChild
这个 content query
:
在运行时,content 的值为施加了 ZippyContentDirective 的 ng-template
代表的 TemplateRef
实例。
这个 Directive 对应的选择器为:appExampleZippyContent
因而也就是下图这个模板:
我冀望最终运行时,可能在页面看到上图模板变量的值被内容投影到 app-example-zippy
外部。
然而理论后果是:
控制台有谬误报出:
ERROR TypeError: Cannot read properties of undefined (reading ‘templateRef’)
at ZippyComponent_div_1_Template (template.html:3:19)
at executeTemplate (core.js:7511:9)
at refreshView (core.js:7380:13)
at refreshEmbeddedViews (core.js:8481:17)
at refreshView (core.js:7404:9)
at refreshComponent (core.js:8527:13)
at refreshChildComponents (core.js:7186:9)
at refreshView (core.js:7430:13)
at refreshComponent (core.js:8527:13)
at refreshChildComponents (core.js:7186:9)
问题剖析
单击 template.html
进入具体引起谬误的代码地位:
主动导航到上图第三行:content.templateRef, 运行时 content 的值为 undefined,因为试图拜访 undefined 的 templateRef
属性,所以报错。
content
的值为空,阐明下图 content query
执行失败了:
@ContentChild(ZippyContentDirective)
我在这个自定义 Directive 的构造函数里设置了断点,然而运行时断点基本就未触发,这只能阐明,Angular 框架基本就没有辨认出该 Directive:
究其原因,在自定义 Directive 所在的 NgModule 定义的 declarations
区域里,没有将该自定义 Directive 增加进去。
将上图 21 行代码勾销正文之后,自定义 Directive 的构造函数立刻被调用了:
留神这里的调用上下文:当自定义 Directive 被增加到 NgModule
的 declarations
区域后,一旦模板解析逻辑检测到该 Directive,就会调用 Angular 的依赖注入相干框架代码,主动生成 Directive 实例:
if (isDirectiveHost(tNode)) {createDirectivesInstances(tView, lView, tNode);
}
总结
本文采取的自定义 Directive,实质上是一个 anchor,用于定位将要被内容投影的模板实例 TemplateRef
.
应用 TemplateRef,组件能够应用 ngTemplateOutlet 指令或 ViewContainerRef 办法 createEmbeddedView() 出现援用的内容。