Angular 基于自定义指令的内容投影 content projection 问题的单步调试
問題描述
本文涉及到的代碼位置:https://github.com/wangzixi-diablo/ngDynamic
我有一個(gè)能接受內(nèi)容投影的 Angular Component:
具體投影內(nèi)容,通過 ng-container 和指令 ngTemplateOutlet 指定。
ngTemplateOutlet 的來(lái)源是 content,這個(gè)屬性是 Component 通過下列 content query 得到的結(jié)果:
@ContentChild(ZippyContentDirective) content!: ZippyContentDirective;從語(yǔ)義上講,消費(fèi) app-example-zippy 的 Component 的 HTML 模板里,只有有 ng-template 元素設(shè)置有自定義指令 ZippyContentDirective 對(duì)應(yīng)的 attribute selector,則該 ng-template 里的內(nèi)容會(huì)被自動(dòng)投影到 app-example-zippy 內(nèi)部。
然而運(yùn)行時(shí),我們觀察不到上圖高亮的第四行內(nèi)容,而是在 console 里看到如下錯(cuò)誤消息:
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 內(nèi)容為 undefined,說(shuō)明 content query 執(zhí)行失敗了:
app-example-zippy 內(nèi)部的 ng-template,使用的 attribute Directive 同ZippyContentDirective 定義的 selector 不一致,如下圖所示:
糾正之后問題消失。
總結(jié)
Ivy 在進(jìn)行渲染時(shí),需要跟蹤三種數(shù)據(jù):Template、Logical Tree 和 Render Tree。在我們的許多數(shù)據(jù)結(jié)構(gòu)中,為了簡(jiǎn)潔起見,這三個(gè)概念被縮寫為 T、L 和 R 前綴。
模板是源代碼的解析版本。它包含以 Ivy 指令和有關(guān)組件/指令的元數(shù)據(jù)的形式呈現(xiàn)模板的指令。如果您可以在源代碼中找到它,那么模板數(shù)據(jù)結(jié)構(gòu)中的相應(yīng)字段也將出現(xiàn)。無(wú)論其中的代碼是否已執(zhí)行,模板信息都存在。例如,即使條件為假,*ngIf 后面的模板仍將具有此模板信息)。
在 Ivy 中,模板信息存儲(chǔ)在 TView(以及 TData 和 TNode)數(shù)據(jù)結(jié)構(gòu)中。這些數(shù)據(jù)結(jié)構(gòu)一起提供了關(guān)于模板 Ivy 在運(yùn)行時(shí)需要的所有靜態(tài)信息。 靜態(tài)這個(gè)詞對(duì)于將其與另一個(gè) Ivy 里重要的 Logic View概念相區(qū)分開。
總結(jié)
以上是生活随笔為你收集整理的Angular 基于自定义指令的内容投影 content projection 问题的单步调试的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《变形金刚 7》电影片段曝光,擎天柱、猩
- 下一篇: 1280*720是多少像素(1K分辨率数