当有嵌套组件时,ng-content 从父作用域中嵌入

kva*_*nck 3 javascript transclusion angular

使用 Angular 2/4,我有一个复杂的页面模板。

假设我有 3 个相互嵌套的组件:page.component, 里面header.component和里面header.title.component有适当设置的自定义选择器。

page.component html模板:

<layout-header></layout-header>
...
Run Code Online (Sandbox Code Playgroud)

header.component html模板:

<section class="dynamic-content" *ngIf="!collapsed" #dynamicContent>
  <layout-header-title></layout-header-title>
  ...
</section>
Run Code Online (Sandbox Code Playgroud)

header.title.component html模板:

<ng-content selector="card-layout-title"></ng-content>
Run Code Online (Sandbox Code Playgroud)

然后,在我的实际页面模板上:

<layout-page>
  <card-layout-title>Title goes here</card-layout-title>
</layout-page>
Run Code Online (Sandbox Code Playgroud)

在ng-content selector="card-layout-title"只有当直接父是在标签内的组件选择,即从工作header.title.component,我无法选择2的水平式的嵌套组件找到内容transclude成card-layout-title。

我该怎么做(最好不要在每个级别添加和传递模板引用,因为每个级别有 5-10 个嵌套组件)?

kva*_*nck 6

我从@dohpaz42 的答案中分离出这些附加信息,因为它与一般用例的相关性要小得多。

如果您的层次结构不完全平坦,即

<layout-dyn-page>
  <layout-header>
    <layout-title>Title</layout-title>
    <layout-summary>Summary</layout-summary>
  <layout-header>
</layout-dyn-page>
Run Code Online (Sandbox Code Playgroud)

上面的解决方案将不起作用,因为ng-content select=不选择不在顶层的元素。当您尝试将它们向下投影时,无论您如何尝试,您都会使用它们的包装标签投影它们,因此当前选择由标签嵌套的元素似乎是不可能的。你必须把它压平,即

<layout-dyn-page>
  <layout-title>Title</layout-title>
  <layout-summary>Summary</layout-summary>
</layout-dyn-page>
Run Code Online (Sandbox Code Playgroud)

这很可能是 angular 中的一个错误(或缺失的功能),但目前(没有文档)我们无法知道。