Angular 内容投影出现 No provider for TemplateRef found 错误的单步调试
問題描述
本文涉及到的代碼位置:https://github.com/wangzixi-diablo/ngDynamic
我有一個(gè)能接受內(nèi)容投影的 Angular Component:
使用如下代碼消費(fèi)這個(gè) Component:
但是遇到運(yùn)行時(shí)錯(cuò)誤,如下圖所示。
點(diǎn)擊 template.html:7:3:
問題分析
拋出該錯(cuò)誤消息的函數(shù)實(shí)現(xiàn):
/*** Returns the value associated to the given token from the NodeInjectors => ModuleInjector.** Look for the injector providing the token by walking up the node injector tree and then* the module injector tree.** This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom* filter. Negative values are reserved for special objects.* - `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)** @param tNode The Node where the search for the injector should start* @param lView The `LView` that contains the `tNode`* @param token The token to look for* @param flags Injection flags* @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`* @returns the value from the injector, `null` when not found, or `notFoundValue` if provided*/ function getOrCreateInjectable(tNode, lView, token, flags = InjectFlags.Default, notFoundValue)第一個(gè)輸入?yún)?shù) tnode 就是 p 節(jié)點(diǎn)本身:
token 指向 TemplateRef:
解決方案
這個(gè)問題有幾種解決方案。
方案1
刪除 p 節(jié)點(diǎn)的自定義 Directive:
然后添加一個(gè)默認(rèn)的內(nèi)容投影:
解決方案2
刪除自定義 Directive 構(gòu)造函數(shù)里的 TemplateRef 依賴:
解決方案3
消費(fèi) zippy Component 時(shí),直接傳入被投影的內(nèi)容:
該內(nèi)容會(huì)被投影到下圖第一行的 place holder:
解決方案4
消費(fèi) Component 時(shí),通過 ng-template + 自定義 Directive 的方式指定被投影的內(nèi)容:
通過 @ContentChild conten query 拿到自定義 Directive 實(shí)例,進(jìn)而拿到 Directive 指向的 TemplateRef:
總結(jié)
渲染樹是實(shí)際的 DOM 渲染樹。 它與 Ivy 的邏輯樹不同,渲染樹必須考慮內(nèi)容投影。 因此渲染樹里的父/子關(guān)系不像邏輯視圖中那樣簡單。
總結(jié)
以上是生活随笔為你收集整理的Angular 内容投影出现 No provider for TemplateRef found 错误的单步调试的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SAP UI5 应用开发教程之四十七 -
- 下一篇: cf手游天赋点在哪(2022CFPL)