在组件标记之间呈现内容

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

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

像这样使用它:

<app-root>Ignored content</app-root>

渲染:

<div>app works!</div>

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

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

由于 Header content hereContentFooter content here都在组件内部,为什么它们没有被忽略,我如何才能做到这一点?

48837 次浏览

Add <ng-content></ng-content> to the component's template where the content should be projected:

@Component({
selector: 'app-demo',
template: '<div>\{\{title}}</div>
<br>
<ng-content></ng-content>',
})
export class DemoComponent {
title = 'Works!';
}

Content to be projected:

<app-demo>This is projected content!</app-demo>

The output will be:

Works!
This is projected content!

Here is a great article about Angular Content Projection (Angular 1 Transclusion): Transclusion in Angular 2 with ng-content