angular - 如何使用 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
在这些包装元素内部显示其自己的内容?通常,投影内容呈现为元素内的叶节点,而我正在寻找可以投影中间节点的东西,然后我的自定义元素可以使用这些中间节点来附加自己的内容。
这里的最佳做法是什么?请在评论之前:
我不是要求使用一些琐碎的内容投影解决方案
<ng-content></ng-content>
,这在这里行不通。不,我不能只是将包装内容移到自定义元素之外。自定义元素可以以多种方式操纵包装投影内容本身。
解决方案
有一种方法,但它不够灵活,如果你只有一个模板要注入,我会使用它。
这个想法是添加<ng-template>
到投影内容并使用指令来获取它的viewContainer
.
然后my-custom-component
你可以得到这个带有ContentChildren
装饰器的 viewContainer 并添加你应该在标签内定义的动态内容。
推荐阅读
- ios - 在 iOS 应用程序中将转发视图置于其他所有内容之上
- python - “'shutil'和'listdir'会在python中引起冲突吗?”
- java - 在 gitlab 上推送新建项目
- java - 克服equals()的不太可能的参数类型的优雅方法:流
似乎与字符串无关 - java - Selenium 如何通过 XPath 访问 WebElement?
- python - 给定一个数字 n 找到最接近它的质数,最大偶数位数
- python - 如何在 PyQt 中向现有 API 添加重载
- java - 重构 lamda 表达式以使用 Comparator.comparingDouble
- android - 为什么自定义标头在 android 中转换为小写,而在 IOS 中在 react native 中可以正常工作
- javascript - JsTree复选框选择具有相应父级的所有字段