问题形容

本文波及到的代码地位:https://github.com/wangzixi-d...

我有一个能承受内容投影的 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 的逻辑树不同,渲染树必须思考内容投影。 因而渲染树里的父/子关系不像逻辑视图中那样简略。