Angular:克隆ng-content元素及其功能

时间:2018-06-29 14:50:58

标签: javascript angular

我正在尝试克隆组件的ng-content项以及该内容的HTML上添加的所有功能。例如,使用该组件的标记可能如下所示:

<custom-component>
  <button (click)="doAThing();">A button</button>
</custom-component>

然后我像这样设置自定义组件的模板:

<ng-template #content>
  <ng-conent></ng-content>
</ng-template>
<ng-template *ngTemplateOutlet="content"></ng-template>
<div class="second-area>
  <ng-template *ngTemplateOutlet="content"></ng-template>
</div>

我期望ng-content将被复制到两个ngTemplateOutlet区域中。发生的情况是它将推送到最后一个出口,而忽略了第一个。此标记可以很好地复制普通标记,但是ng-content仅移动到一个出口。

这种技术是否无法实现?我是否缺少明显的东西,或者它是克隆ng-content的内容以及与其相关的任何事件的另一种方法?

1 个答案:

答案 0 :(得分:0)

我找到了适合我的解决方案。首先是HTML,您需要一个指令来包装内容,以便您可以引用它。您需要在指令中使用星号,以便可以复制它。

<custom-component>
  <ng-container *customDirective>
    <button (click)="doAThing();">A button</button>
  </ng-container>
</custom-component>

该指令不需要任何额外的代码。我们只需要参考即可。

在您的自定义组件中,您需要通过@ContentChild创建对指令的引用,如下所示:

@ContentChild(CustomDirective, { read: TemplateRef }) transcludeTemplate;

然后,将以下内容用于自定义组件HTML,避免同时使用ng-content标签:

<ng-template *ngTemplateOutlet="transcludeTemplate"></ng-template>
<div class="second-area>
  <ng-template *ngTemplateOutlet="transcludeTemplate"></ng-template>
</div>

因此,这实际上与复制<ng-content>并不相同,但是它为我们提供了类似的功能。显然,ng内容未相乘为intended behavior。因此,这可能是实现类似目标的最佳方法。