htmlangularangular-ng-ifng-template

How to include an ng-template element without a condition in Angular 2


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?


Solution

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