angular - 在嵌套组件中链接包含

标签 angular

我有以下嵌套组件结构。

<app-root>
    <app-comp-1>
      <app-comp-2>
      </app-comp-2>
   </app-comp-1>
  <app-root>

我想将任何内容嵌入到最后一个子项 (app-comp-2) 中。所以,我需要这样的东西。

<app-comp-1>
    <app-comp-2>
        <ng-content></ng-content>
    </app-comp-2>
</app-comp-1>

但是在 app-root 组件中只有 app-comp-1 组件可用。所以,这是我必须嵌入我的内容的地方。

<app-root>
    <app-comp-1>
        <content-I-want-to-transclude></content-I-want-to-transclude>
    </app-comp-1>
</app-root>
 ---------------------------
<app-comp-1>
    <ng-content></ng-content>
    <app-comp-2>
        ...
    </app-comp-2>
</app-comp-1>

所以我需要一个解决方案来获取已嵌入到第一个组件中的内容并将其传递给第二个组件。

Plunker

最佳答案

This Github issue使用 ngProjectAs 属性为这个问题提供了一个很好的解决方案。

在有 2 层内容投影的情况下,第一层使用带有 ngProjectAs 属性的 ng-content 元素,以及下一个选择器。

第二层使用另一个ng-content,并选择第一层的ngProjectAs属性的值:

一级(父组件):

<ng-content select="my-component" ngProjectAs="arbitrary-selector"></ng-content>

第 2 级(嵌套子组件):

<ng-content select="arbitrary-selector"></ng-content>

用法:

<my-app>
  <my-component>My Projected Content</my-component>
</my-app>

结果 DOM:

<my-app>
  <my-component>
      <nested-component>My Projected Content</nested-component>
  </my-component>
</my-app>

关于angular - 在嵌套组件中链接包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41247414/

相关文章:

javascript - 如何在 Angular 4 中使用路由器 url 通配符?

html - Bootstrap 下拉菜单 Angular2 不工作

angular - 在 Docker 容器中运行 Angular 通用应用程序

javascript - Angular2 指令分配给模板

javascript - "CUSTOM_ELEMENTS_SCHEMA"Angular 2 App 测试错误

javascript - Angular 4 中从一个组件到另一组件的数据

angular - 如何不从 ngrx 存储中获取空值

javascript - 在 Typescript 中使用多个字符串数组

angular - 在 *ngFor 循环中创建空白行

javascript - ng如果不更新 DOM