在组件标记之间渲染内容

Lea*_*ava 37 shadow-dom angular

呈现组件时,将忽略其中的内容,例如:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: '<div>{{title}}</div>',
})
export class AppComponent {
  title = 'app works!';
}
Run Code Online (Sandbox Code Playgroud)

使用它像:

<app-root>Ignored content</app-root>
Run Code Online (Sandbox Code Playgroud)

呈现:

<div>app works!</div>
Run Code Online (Sandbox Code Playgroud)

但是看看PrimeNg对话框,他们使用这样的组件:

<p-dialog [(visible)]="display">
    <p-header>
        Header content here
    </p-header>
    Content
    <p-footer>
        Footer content here
   </p-footer>
</p-dialog>
Run Code Online (Sandbox Code Playgroud)

作为Header content here,Content并且Footer content here在组件内部,为什么它们不被忽略,我怎样才能实现这一目标?

Sei*_*vic 85

添加<ng-content></ng-content>到应该投影内容的组件模板:

@Component({
  selector: 'app-root',
  template: '<div>{{title}}</div>
             <br>
             <ng-content></ng-content>',
})
export class AppComponent {
  title = 'app works!';
}
Run Code Online (Sandbox Code Playgroud)

要投影的内容:

<app-root>This is projected content!</app-root>
Run Code Online (Sandbox Code Playgroud)

输出将是:

app works!
This is projected content!
Run Code Online (Sandbox Code Playgroud)

这是一篇关于角度内容投影(Angular 1 Transclusion)的伟大文章:Angular 2中的ng-content中的Transclusion

  • 知道如何访问组件内 &lt;ng-content&gt; 内的内容吗? (2认同)
  • @Shilpa 您可以使用“@ContentChild”和“@ContentChildren”来访问投影内容。 (2认同)
  • 我很惊讶这个答案得到了如此多的赞成,因为它显示了非工作示例。通过查看 [here](/sf/ask/2279816591/) 你会看到 `ng-content` 不能在 `index.html` 中使用,其中`app-root` 首先被初始化。 (2认同)
  • 例如,@ YuriyKravetsso,我对其进行了投票,因为它解释了如何显示在组件标签之间添加的内容,我不在乎示例 (2认同)