问题描述本文涉及到的代码位置:https://github.com/wangzixi-diablo/ngDynamic
<ng-container [ngTemplateOutlet]="content.templateRef"></ng-container> 这里需要接受一个类型为 content.templateRef 在哪里赋的值? 使用了 在运行时,content 的值为施加了 ZippyContentDirective 的 这个 Directive 对应的选择器为: 因此也就是下图这个模板: 我期望最终运行时,能够在页面看到上图模板变量的值被内容投影到 然而实际结果是: 控制台有错误报出: 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) 问题分析单击 自动导航到上图第三行:content.templateRef, 运行时 content 的值为undefined,因为试图访问 undefined 的
@ContentChild(ZippyContentDirective) 我在这个自定义 Directive 的构造函数里设置了断点,但是运行时断点根本就未触发,这只能说明,Angular 框架根本就没有识别出该 Directive: 究其原因,在自定义 Directive 所在的 NgModule 定义的 将上图21行代码取消注释之后,自定义 Directive 的构造函数立即被调用了: 注意这里的调用上下文:当自定义 Directive 被添加到 if (isDirectiveHost(tNode)) { createDirectivesInstances(tView, lView, tNode); } 总结本文采取的自定义 Directive,本质上是一个 anchor,用于定位将要被内容投影的模板实例 使用 TemplateRef,组件可以使用 ngTemplateOutlet 指令或 ViewContainerRef 方法 createEmbeddedView() 呈现引用的内容。 |
|