ngTemplateOutlet
is a structural directive. It instantiates a template dynamically using a template reference and context object as parameters. We use it to insert a template (created by ngTemplate
) in various sections of our DOM.
Defining a Template
Before we can use ngTemplateOutlet
we must first define a template using <ng-template>
. The template is the body of the <ng-template>
element.
<ng-template #myTemplate>
<div>Hello template</div>
</ng-template>
To reference the template we name it via #
syntax. By adding #myTemplate
to the element we can get a reference to the template using the name myTemplate
. The type of myTemplate
is TemplateRef
.
Rendering a Template
The content of a <ng-Template>
element is not rendered in the browser. To have the template body rendered we must now pass the template reference to a ngTemplateOutlet
.
<!-- Define our template -->
<ng-template #myTemplate> World! </ng-template>
Hello
<!-- Render the template in this outlet -->
<ng-container [ngTemplateOutlet]="myTemplate"></ng-container>
Passing data to ngTemplateOutlet
We can also pass data to the template by using ngTemplateOutletContext
.
<ng-container [ngTemplateOutlet]="myTemplate"
[ngTemplateOutletContext] ="{value:'1000'}">
</ng-container>
Alternatively we can also use the following syntax:
<ng-container *ngTemplateOutlet="myTemplate; context:{value:100}">
</ng-container>
Using the Context in the template
To access the context in our template we use let-*
syntax to define template input variables.
<ng-template #myTemplate let-params="value">
<div>Hello template {{ params }} </div>
</ng-template>
Using $implicit
If you use the key $implicit
in the context object will set its value as default for all the local variables.
For Example we have not assigned anything to the let-name
so it will take the value from the $implicit
, which is Guest
.
ng-template let-name let-message="message" #myTemplate>
<p>Dear {{name}} , {{message}} </p>
</ng-template>
<ng-container [ngTemplateOutlet]="myTemplate"
[ngTemplateOutletContext] ="{$implicit:'Guest',message:'Welcome to our site'}">
</ng-container>
And in the following code, both name
& message
gets the value from the $implicit
i.e Guest
<ng-template let-name let-message #musterTemplate>
<p>Dear {{name}} , {{message}} </p>
</ng-template>
<ng-container [ngTemplateOutlet]="musterTemplate"
[ngTemplateOutletContext] ="{$implicit:'Guest',message:'Welcome to our site'}">
</ng-container>