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

Vla*_*vic 6 angular2-template angular

我很好奇有没有办法在组件中重复使用两次ng-content?或者将它分配给组件构造函数中的变量?

就像是:

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

Nav*_*T P 11

还有另一种方法可以帮助 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>
Run Code Online (Sandbox Code Playgroud)

用这个,

<my-component>Anything</my-component>
Run Code Online (Sandbox Code Playgroud)

  • 它工作得很好,但最新的角度版本(8+)将失败,因为同一个 ng-container 上有两个绑定。需要包装到额外的容器中:`&lt;ng-container *ngIf&gt;&lt;ng-container *ngTemplateOutlet&gt;&lt;/ng-container&gt;&lt;/ng-container&gt;` (4认同)

Vla*_*vic 4

是的,我也发现了这个。

<my-component> <div content-a> A </div> </my-component>
Run Code Online (Sandbox Code Playgroud)

并在组件中:

<ng-content select="[content-a]"></ng-content>
Run Code Online (Sandbox Code Playgroud)