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

问题描述
本文涉及到的代码位置:https://github.com/wangzixi-diablo/ngDynamic
我有一个能接受内容投影的 Angular Component:

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

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


问题分析
抛出该错误消息的函数实现:
复制代码
第一个输入参数 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
的逻辑树不同,渲染树必须考虑内容投影。 因此渲染树里的父/子关系不像逻辑视图中那样简单。
版权声明: 本文为 InfoQ 作者【Jerry Wang】的原创文章。
原文链接:【http://xie.infoq.cn/article/befce59e2432dd5c8eb9c412a】。文章转载请联系作者。
评论