【问题标题】:Is it possible to reuse <ng-content></ng-content> in component template? Angular2是否可以在组件模板中重用 <ng-content></ng-content> ?角2
【发布时间】:2015-12-25 09:02:47
【问题描述】:

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

类似:

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

【问题讨论】:

  • 是的,我们可以在模板中使用多个 ng-content,但如果我们使用多个,则必须提及 ng-content 的名称。我发现的 ng-content 的最佳教程在这里angular-tips.com/blog/2015/09/migrating-directives-to-angular-2
  • 是的,我也发现了这个。
     
    A
    B
    并且在组件中:
  • 是的,这个也可以用。

标签: angular angular2-template


【解决方案1】:

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>

【讨论】:

  • 它运行良好,但最新的 Angular 版本 (8+) 会因为同一个 ng-container 上的两个绑定而失败。需要包装到额外的容器中:&lt;ng-container *ngIf&gt;&lt;ng-container *ngTemplateOutlet&gt;&lt;/ng-container&gt;&lt;/ng-container&gt;
【解决方案2】:

是的,我也发现了这个。

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

在组件中:

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

【讨论】:

    猜你喜欢
    • 2019-11-28
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2017-08-28
    相关资源
    最近更新 更多