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.

3
  • so the question is not about ngIf, you just showed it as an analogy? Commented Jul 5, 2017 at 5:48
  • I really don't see why you wouldn't use a component. That's what they're for. Commented Jul 5, 2017 at 6: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! Commented Apr 7, 2023 at 5:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.