Angular模板中的可重用片段

4 angular-ng-if angular2-template angular

我们现在可以有else片段,指的是<ng-template>:

<div *ngIf="condition; else not">
  Condition satisfied.
  <ng-template #not>
    Condition not satisfied.
  </ng-template>
</div>
Run Code Online (Sandbox Code Playgroud)

我想是能够引用片段的上下文之外*ngIf--something像

<div>DIV1 <ng-template-call template="shared"></ng-template-call></div>
<div>DIV2 <ng-template-call template="shared"></ng-template-call></div>

<ng-template #shared>This is a shared snippet.</ng-template>
Run Code Online (Sandbox Code Playgroud)

ng-template-call上面我所说的正确方法是什么?

是的,我知道我可以把它变成一个单独的组件,但它没有达到那个水平.我总是可以写:

<div *ngIf="false; else shared">
Run Code Online (Sandbox Code Playgroud)

但这看起来很笨拙.

小智 11

我认为Transclusions正是您所寻找的

这是一个示例:

<ng-container [ngTemplateOutlet]="reusable"></ng-container>

<ng-template #resusable>...</ng-template>
Run Code Online (Sandbox Code Playgroud)

供参考:https://toddmotto.com/transclusion-in-angular-2-with-ng-content