有没有办法将容器或包装器标记作为投影内容传递给组件?
以下是一些代码:
这就是我想要的方式
<my-component>
<div class="wrapper">
<ng-content></ng-content>
</div>
</my-component>
组件
@Component({
selector: 'my-component',
template: `
<ng-content select=".wrapper">
<h1>Hello World</h1>
</ng-content>
`
})
export class MyComponent {}
答案 0 :(得分:1)
所以,一年多以后,我终于知道该怎么做了:)
您可以使用<ng-template />
和ngTemplateOutlet
将包装器/容器模板传递给组件。
import { Component, ContentChild, Input, TemplateRef, ViewChild } from '@angular/core';
@Component({
selector: 'useful-generic',
template: `
<ng-container *ngTemplateOutlet="wrapper; context: {$implicit: body}"></ng-container>
<ng-template #body>
<ng-content></ng-content>
</ng-template>
<ng-template #defaultWrapper let-content>
<div class="default-wrapper">
<ng-container *ngTemplateOutlet="content"></ng-container>
</div>
</ng-template>
`
})
export class UsefulGenericComponent {
@ContentChild('wrapper') wrapper: TemplateRef<any>;
@ViewChild('defaultWrapper') defaultWrapper: TemplateRef<any>;
ngAfterContentInit() {
if (!this.wrapper) {
this.wrapper = this.defaultWrapper;
}
}
}
示例1:
<useful-generic>
<h1>Hello from inside default wrapper</h1>
</useful-generic>
输出1:
<useful-generic>
<div class="default-wrapper">
<h1>Hello from inside default wrapper</h1>
</div>
</useful-generic>
示例2:
<useful-generic>
<h1>Hello from inside my wrapper</h1>
<ng-template #wrapper let-content>
<div class="my-very-own-wrapper">
<ng-container *ngTemplateOutlet="content"></ng-container>
</div>
</ng-template>
</useful-generic>
输出2:
<useful-generic>
<div class="my-very-own-wrapper">
<h1>Hello from inside my wrapper</h1>
</div>
</useful-generic>