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?
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 .
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.
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.
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.
<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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With