20

I need an HTML fragment more than once in my Angular template. Instead of writing the HTML code multiple times, I decided to put it inside an ng-template element and use that element replicated in the code.

For example:

<ng-template #myTemplate>
  <h1>Some Header</h1>
  <p>Some text...</p>
</ng-template>

How can I now include this ng-template element somewhere in the template?

I know, that this is possible by using an ngIf statement, like so:

<div *ngIf="false; else myTemplate"></div>

However, this feels like a dirty hack to me. Is there another possibility?

user7346048
  • 650
  • 8
  • 15

2 Answers2

24
  <ng-template #myTemplate>
      <h1>Some Header</h1>
      <p>Some text...</p>
  </ng-template>

  <ng-container *ngTemplateOutlet="myTemplate">
  </ng-container>

We can definitely use 'ng-container' to instantiate the 'myTemplate' template on the page.

We are referring to the 'myTemplate' template via its template reference #myTemplate, and we are using the ngTemplateOutlet structural directive to render the template.

ngTemplateOutlet directive inserts an embedded view from a prepared TemplateRef.

1

You are right. Doing it with an ngIf and a hardcoded "false" value is not the right way to go here. What you are looking for is the NgTemplateOutlet directive:

https://angular.io/api/common/NgTemplateOutlet

Patrick Kelleter
  • 2,327
  • 1
  • 9
  • 18