没有包装标签的 Angular 包含

标签 angular angular-template transclusion

如何在不包含包装标签的情况下在 Angular 中进行槽嵌入?

例如:

这是带有选择器 my-component 的组件模板:

<div class="my-component">
   <p class="some sensitive css-classes">
       <ng-content select="sub-header"></ng-content>
   </p>

   <p class="more sensitive css-classes">
       <ng-content select="sub-footer"></ng-content>
   </p>
</div>

这是用数据填充模板的组件之一

<my-component>
    <sub-header>
        Very <strong>important</strong> text with tags.
    </sub-header>

    <sub-footer>
        More <em>important</em> text with tags.
    </sub-footer>
</my-component>

嵌入结果看起来是这样的:

<div class="my-component">
   <p class="some sensitive css-classes">
       <sub-header>
          Very <strong>important</strong> text with tags.
       </sub-header>
   </p>

   <p class="more sensitive css-classes">
       <sub-footer>
           More <em>important</em> text with tags.
       </sub-footer>
   </p>
</div>

这不是很有用,因为语义和非常敏感的 CSS 样式

我怎样才能得到像这样的嵌入:

<div class="my-component">
   <p class="some sensitive css-classes">
       Very <strong>important</strong> text with tags.
   </p>

   <p class="more sensitive css-classes">
       More <em>important</em> text with tags.
   </p>
</div>

与其他问题的主要区别在于dom的嵌入。

最佳答案

您可以在 ng-container 标签上使用 ngProjectAs angular 属性

<my-component>
  <ng-container ngProjectAs="sub-header">
    Very 
    <strong>important</strong> text with tags.
  </ng-container>
  <ng-container ngProjectAs="sub-footer">
    More 
    <em>important</em> text with tags.
  </ng-container>
</my-component>

Stackblitz Example

有关文档,请查看 https://github.com/angular/angular.io/issues/1683

关于没有包装标签的 Angular 包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47930321/

相关文章:

angular - IE9 PathLocationStrategy Angular 4

Angular - 根据下拉列表值显示或隐藏

angularjs - CRUD 详细信息屏幕,有条件的新建或编辑

javascript - Angular2,从组件内的字符串评估模板

string - YAML引用另一个文件中的另一个变量

Angular2 ViewChildren 与嵌入相结合

angular - 动态插入 ng-content 选择

angular - 带管道的 ngx 图表数据

angular - 在 Angular 5 应用程序中导入第三方 js 库 cq-prolyfill 的正确方法

angularjs - 具有动态生成的输入字段的 Angular 指令无法显示验证