是否可以在组件模板中重用 <ng-content></ng-content>?角度2

Is it possible to reuse <ng-content></ng-content> in component template? Angular2

我很好奇有什么方法可以在组件中重复使用两次ng-content?或者将其分配给组件构造函数内的变量?

类似于:

@Component({
    selector: "component"
})
@View({
    template: `<ng-content></ng-content> and again <ng-content></ng-content>`
})

是的,我也找到了这个。

<my-component> <div content-a> A </div> </my-component>

并在组件中:

<ng-content select="[content-a]"></ng-content>

ng-template

的帮助下还有另一种方法

ng-content 包裹在 ng-template 中,并使用 ngTemplateOutletng-container

示例:

<ng-container *ngIf="YourCondition" *ngTemplateOutlet="content"></ng-container>
<ng-container *ngIf="!YourCondition" *ngTemplateOutlet="content"></ng-container>

<ng-template #content><ng-content></ng-content></ng-template>

用作,

<my-component>Anything</my-component>