使用 Angular 2/4,我有一个复杂的页面模板。
假设我有 3 个相互嵌套的组件:page.component
,在 header.component
内和在 header.title.component
内适当设置自定义选择器。
page.component
html 模板:
<layout-header></layout-header>
...
header.component
html 模板:
<section class="dynamic-content" *ngIf="!collapsed" #dynamicContent>
<layout-header-title></layout-header-title>
...
</section>
header.title.component
html 模板:
<ng-content selector="card-layout-title"></ng-content>
然后,在我的实际页面模板上:
<layout-page>
<card-layout-title>Title goes here</card-layout-title>
</layout-page>
ng-contentselector="card-layout-title"
仅当直接父级是内部带有要选择的标签的组件时才有效,即来自 header.title.component
我无法选择 2 层以上的嵌套组件来查找要嵌入到 card-layout-title
中的内容。
我该如何做到这一点(最好不要添加模板引用并将其传递到每个级别,因为每个级别有 5-10 个嵌套组件)?
最佳答案
我将这些附加信息从 @dohpaz42 的答案中分离出来,因为它与一般用例的相关性要小得多。
如果您的等级制度不完全平坦,即
<layout-dyn-page>
<layout-header>
<layout-title>Title</layout-title>
<layout-summary>Summary</layout-summary>
<layout-header>
</layout-dyn-page>
上述解决方案将不起作用,因为 ng-content select=
不会选择不在顶层的元素。当您尝试向下投影它们时,无论您如何尝试,都会使用它们的包装标签来投影它们,因此当前选择嵌套在 by 标签内的元素似乎是不可能的。您必须将其压平,即
<layout-dyn-page>
<layout-title>Title</layout-title>
<layout-summary>Summary</layout-summary>
</layout-dyn-page>
这很可能是 Angular 中的一个错误(或缺少功能),但目前(没有文档)我们无法知道。
关于javascript - 当存在嵌套组件时,ng-content 从父级作用域中嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45273437/