likes
comments
collection
share

Angular 内容投影 content projection 关于条件渲染问题的单步调试

作者站长头像
站长
· 阅读数 30

问题描述

本文涉及到的代码位置:https://github.com/wangzixi-d...

ng-containerngTemplateOutlet 的配合使用。

<ng-container [ngTemplateOutlet]="content.templateRef"></ng-container>

这里需要接受一个类型为 TemplateRef 的输入:

Angular 内容投影 content projection 关于条件渲染问题的单步调试

content.templateRef 在哪里赋的值?

使用了 ContentChild 这个 content query

Angular 内容投影 content projection 关于条件渲染问题的单步调试

在运行时,content 的值为施加了 ZippyContentDirective 的 ng-template 代表的 TemplateRef 实例。

这个 Directive 对应的选择器为:appExampleZippyContent

Angular 内容投影 content projection 关于条件渲染问题的单步调试

因此也就是下图这个模板:Angular 内容投影 content projection 关于条件渲染问题的单步调试

我期望最终运行时,能够在页面看到上图模板变量的值被内容投影到 app-example-zippy 内部。

然而实际结果是:

Angular 内容投影 content projection 关于条件渲染问题的单步调试

控制台有错误报出:

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 进入具体引起错误的代码位置:

Angular 内容投影 content projection 关于条件渲染问题的单步调试

Angular 内容投影 content projection 关于条件渲染问题的单步调试

自动导航到上图第三行:content.templateRef, 运行时 content 的值为undefined,因为试图访问 undefined 的 templateRef 属性,所以报错。

content 的值为空,说明下图 content query 执行失败了:

@ContentChild(ZippyContentDirective)

Angular 内容投影 content projection 关于条件渲染问题的单步调试

我在这个自定义 Directive 的构造函数里设置了断点,但是运行时断点根本就未触发,这只能说明,Angular 框架根本就没有识别出该 Directive:Angular 内容投影 content projection 关于条件渲染问题的单步调试

究其原因,在自定义 Directive 所在的 NgModule 定义的 declarations 区域里,没有将该自定义 Directive 添加进去。

Angular 内容投影 content projection 关于条件渲染问题的单步调试

将上图21行代码取消注释之后,自定义 Directive 的构造函数立即被调用了:

Angular 内容投影 content projection 关于条件渲染问题的单步调试

注意这里的调用上下文:当自定义 Directive 被添加到 NgModuledeclarations 区域后,一旦模板解析逻辑检测到该 Directive,就会调用 Angular 的依赖注入相关框架代码,自动生成 Directive 实例:

Angular 内容投影 content projection 关于条件渲染问题的单步调试

Angular 内容投影 content projection 关于条件渲染问题的单步调试

 if (isDirectiveHost(tNode)) {
        createDirectivesInstances(tView, lView, tNode);
    }

总结

本文采取的自定义 Directive,本质上是一个 anchor,用于定位将要被内容投影的模板实例 TemplateRef.

使用 TemplateRef,组件可以使用 ngTemplateOutlet 指令或 ViewContainerRef 方法 createEmbeddedView() 呈现引用的内容。