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

举报
Jerry Wang 发表于 2022/10/03 11:21:18 2022/10/03
【摘要】 问题描述本文涉及到的代码位置:https://github.com/wangzixi-diablo/ngDynamicng-container 和 ngTemplateOutlet 的配合使用。<ng-container [ngTemplateOutlet]="content.templateRef"></ng-container>这里需要接受一个类型为 TemplateRef 的输入:c...

问题描述

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

ng-containerngTemplateOutlet 的配合使用。

<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 被添加到 NgModuledeclarations 区域后,一旦模板解析逻辑检测到该 Directive,就会调用 Angular 的依赖注入相关框架代码,自动生成 Directive 实例:

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

总结

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

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

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。