4

We can now have else snippets, referring to an <ng-template>:

<div *ngIf="condition; else not">
  Condition satisfied.
  <ng-template #not>
    Condition not satisfied.
  </ng-template>
</div>

I would like to be able to refer to snippets outside of the context of an *ngIf--something like

<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>

What is the correct way to write what I have called ng-template-call above?

Yes, I know I could make this into a separate component, but it does not rise to that level. And I could always write:

<div *ngIf="false; else shared">

but that seems clumsy.

  • so the question is not about `ngIf`, you just showed it as an analogy? – Max Koretskyi Jul 05 '17 at 05:48
  • I really don't see why you wouldn't use a component. That's what they're for. – JB Nizet Jul 05 '17 at 06:39
  • The #1 reason you wouldn't (want to) use a component is if you don't want a wrapping element. The best general solution to this is `display: contents` which makes the component element behave like it wasn't there. But if there's ever a way to make a component with an optional wrapper I'll be the first to use it! – Simon_Weaver Apr 07 '23 at 05:45

1 Answers1

11

I think Transclusions is what you're looking for

Here's a sample:

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

<ng-template #resusable>...</ng-template>

For reference: https://toddmotto.com/transclusion-in-angular-2-with-ng-content

wbtubog
  • 164
  • 4