乐趣区

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

问题形容

本文波及到的代码地位:https://github.com/wangzixi-d…

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

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

ngTemplateOutlet 的起源是 content,这个属性是 Component 通过下列 content query 失去的后果:

@ContentChild(ZippyContentDirective) content!: ZippyContentDirective;

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

然而运行时,咱们察看不到上图高亮的第四行内容,而是在 console 里看到如下谬误音讯:

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 执行失败了:

app-example-zippy 外部的 ng-template,应用的 attribute Directive 同ZippyContentDirective 定义的 selector 不统一,如下图所示:

纠正之后问题隐没。

总结

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

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

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

退出移动版