ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-03-05 11:01:28  阅读:230  来源: 互联网

标签:自定义 Directive No 投影 param injector token provider 单步


问题描述

本文涉及到的代码位置: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 的逻辑树不同,渲染树必须考虑内容投影。 因此渲染树里的父/子关系不像逻辑视图中那样简单。

标签:自定义,Directive,No,投影,param,injector,token,provider,单步
来源: https://www.cnblogs.com/sap-jerry/p/15967237.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有