在组件标签之间渲染内容
Render content between the component tags
渲染组件时,会忽略其中的内容,例如:
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 here
、Content
和 Footer content here
在组件内部,为什么它们没有被忽略,我该如何实现?
将 <ng-content></ng-content>
添加到应投影内容的组件模板:
@Component({
selector: 'app-demo',
template: '<div>{{title}}</div>
<br>
<ng-content></ng-content>',
})
export class DemoComponent {
title = 'Works!';
}
待投射内容:
<app-demo>This is projected content!</app-demo>
输出将是:
Works!
This is projected content!
这是一篇关于 Angular 内容投影(Angular 1 嵌入)的精彩文章:Transclusion in Angular 2 with ng-content
渲染组件时,会忽略其中的内容,例如:
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 here
、Content
和 Footer content here
在组件内部,为什么它们没有被忽略,我该如何实现?
将 <ng-content></ng-content>
添加到应投影内容的组件模板:
@Component({
selector: 'app-demo',
template: '<div>{{title}}</div>
<br>
<ng-content></ng-content>',
})
export class DemoComponent {
title = 'Works!';
}
待投射内容:
<app-demo>This is projected content!</app-demo>
输出将是:
Works!
This is projected content!
这是一篇关于 Angular 内容投影(Angular 1 嵌入)的精彩文章:Transclusion in Angular 2 with ng-content