Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 876
user7346048 Avatar asked Feb 21 '18 13:02

user7346048


People also ask

How do I access ng-template in component?

To access the above ng-template in the component or directive, first, we need to assign a template reference variable. #sayHelloTemplate is that variable in the code below. Now, we can use the ViewChild query to inject the sayHelloTemplate into our component as an instance of the class TemplateRef .

Can we apply ngIf to ng-template?

the element onto which the structural directive ngIf was applied has been moved into an ng-template. The expression of *ngIf has been split up and applied to two separate directives, using the [ngIf] and [ngIfElse] template input variable syntax.

What is pTemplate in ng-template?

pTemplate is a custom-made directive by PrimeNG. Its purpose is to link a template defined by you (the user) to a container defined by the library (PrimeNG). That enables the user to provide a custom template that is displayed inside a component made by the library.

What is TemplateRef and ViewContainerRef in Angular?

TemplateRef is an embedded template which you can use in ViewContainerRef. createEmbeddedView to create Embedded View. *ngFor is doing the same, it reads the element as a TemplateRef and injects mutiple times to create view with data. TemplateRef cannot be used as an element for css decorations in .ts.


2 Answers

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

like image 96
Dilushika Weerawardhana Avatar answered Oct 22 '22 03:10

Dilushika Weerawardhana


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

like image 1
Patrick Kelleter Avatar answered Oct 22 '22 04:10

Patrick Kelleter