0
点赞
收藏
分享

微信扫一扫

Angular 基于自定义指令的内容投影 content projection 问题的单步调试

水沐由之 2022-03-11 阅读 68


问题描述

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

我有一个能接受内容投影的 Angular Component:

Angular 基于自定义指令的内容投影 content projection 问题的单步调试_html

具体投影内容,通过 ​​ng-container​​​ 和指令 ​​ngTemplateOutlet​​ 指定。

​ngTemplateOutlet​​​ 的来源是 ​​content​​,这个属性是 Component 通过下列 content query 得到的结果:

Angular 基于自定义指令的内容投影 content projection 问题的单步调试_数据_02

@ContentChild(ZippyContentDirective) content!: ZippyContentDirective;

从语义上讲,消费 app-example-zippy 的 Component 的 HTML 模板里,只有有 ​​ng-template​​​ 元素设置有自定义指令 ​​ZippyContentDirective​​​ 对应的 attribute selector,则该 ​​ng-template​​​ 里的内容会被自动投影到 ​​app-example-zippy​​ 内部。

Angular 基于自定义指令的内容投影 content projection 问题的单步调试_数据_03

然而运行时,我们观察不到上图高亮的第四行内容,而是在 console 里看到如下错误消息:

Angular 基于自定义指令的内容投影 content projection 问题的单步调试_数据结构_04


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 内容为 undefined,说明 content query 执行失败了:

Angular 基于自定义指令的内容投影 content projection 问题的单步调试_html_05

app-example-zippy 内部的 ​​ng-template​​​,使用的 attribute Directive 同​​ZippyContentDirective​​ 定义的 selector 不一致,如下图所示:

Angular 基于自定义指令的内容投影 content projection 问题的单步调试_html_06

Angular 基于自定义指令的内容投影 content projection 问题的单步调试_数据结构_07

纠正之后问题消失。

Angular 基于自定义指令的内容投影 content projection 问题的单步调试_html_08

总结

Ivy 在进行渲染时,需要跟踪三种数据:Template、Logical Tree 和 Render Tree。在我们的许多数据结构中,为了简洁起见,这三个概念被缩写为 T、L 和 R 前缀。

模板是源代码的解析版本。它包含以 Ivy 指令和有关组件/指令的元数据的形式呈现模板的指令。如果您可以在源代码中找到它,那么模板数据结构中的相应字段也将出现。无论其中的代码是否已执行,模板信息都存在。例如,即使条件为假,​​*ngIf​​ 后面的模板仍将具有此模板信息)。

在 Ivy 中,模板信息存储在 TView(以及 TData 和 TNode)数据结构中。这些数据结构一起提供了关于模板 Ivy 在运行时需要的所有静态信息。 ​​静态​​​这个词对于将其与另一个 Ivy 里重要的 ​​Logic View​​概念相区分开。



举报

相关推荐

0 条评论