首页 > 解决方案 > 如何使用 Angular 组件嵌入投影自定义中间内容?

问题描述

Angular 中是否有解决方案来指定包含/中间内容的投影,以进一步将内容包装到允许投影的组件内部?例如,假设我想自定义我的自定义组件用来生成这个最终输出的包装器:

<my-custom-component>
    <fieldset>
        <legend>{{ titleOfCustomComponent }}</legend>
        <!-- Content internal to `my-custom-component` then rendered here -->
    </fieldset>
</my-custom-component>

您可以想象,在非表单上下文中,可能不适合使用 fieldset 元素,因此,也许一个简单的 div 更有用:

<my-custom-component>
    <div>
        <h1>{{ titleOfCustomComponent }}</h1>
        <!-- Content internal to `my-custom-component` then rendered here -->
    </div>
</my-custom-component>

如何将这些包装元素投射到内部my-custom-component,同时仍然允许my-custom-component在这些包装元素内部显示其自己的内容?通常,投影内容呈现为元素内的叶节点,而我正在寻找可以投影中间节点的东西,然后我的自定义元素可以使用这些中间节点来附加自己的内容。

这里的最佳做法是什么?请在评论之前:

  1. 我不是要求使用一些琐碎的内容投影解决方案<ng-content></ng-content>,这在这里行不通。

  2. 不,我不能只是将包装内容移到自定义元素之外。自定义元素可以以多种方式操纵包装投影内容本身。

标签: angular

解决方案


有一种方法,但它不够灵活,如果你只有一个模板要注入,我会使用它。

这个想法是添加<ng-template>到投影内容并使用指令来获取它的viewContainer.

然后my-custom-component你可以得到这个带有ContentChildren装饰器的 viewContainer 并添加你应该在标签内定义的动态内容。

这是这种方法的一个例子


推荐阅读