Angular 内容投影出现 No provider for TemplateRef found 错误的单步调试

举报
Jerry Wang 发表于 2022/10/31 22:53:10 2022/10/31
【摘要】 问题描述本文涉及到的代码位置:https://github.com/wangzixi-diablo/ngDynamic我有一个能接受内容投影的 Angular Component:使用如下代码消费这个 Component:但是遇到运行时错误,如下图所示。点击 template.html:7:3: 问题分析抛出该错误消息的函数实现:/** * Returns the value associ...

问题描述

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

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

使用如下代码消费这个 Component:

但是遇到运行时错误,如下图所示。
点击 template.html:7:3:


问题分析

抛出该错误消息的函数实现:

/**
 * 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)

第一个输入参数 tnode 就是 p 节点本身:

token 指向 TemplateRef

解决方案

这个问题有几种解决方案。

方案1

删除 p 节点的自定义 Directive:

然后添加一个默认的内容投影:

解决方案2

删除自定义 Directive 构造函数里的 TemplateRef 依赖:

解决方案3

消费 zippy Component 时,直接传入被投影的内容:

该内容会被投影到下图第一行的 place holder:

解决方案4

消费 Component 时,通过 ng-template + 自定义 Directive 的方式指定被投影的内容:

通过 @ContentChild conten query 拿到自定义 Directive 实例,进而拿到 Directive 指向的 TemplateRef

总结

渲染树是实际的 DOM 渲染树。 它与 Ivy 的逻辑树不同,渲染树必须考虑内容投影。 因此渲染树里的父/子关系不像逻辑视图中那样简单。

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

评论(0

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

全部回复

上滑加载中

设置昵称

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

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

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