What does <ng-template> do?
In Angular, <ng-template> is a template element that is not rendered into the DOM on its own, but holds markup that Angular can insert into the DOM dynamically.
Main points
- Lazy loading/deferred rendering:
html
<ng-template #tpl>
<p>Hello, world!</p>
</ng-template>- The
<p>will not appear in the DOM until the template is explicitly used (viangTemplateOutletor a structural directive).
- Use with
*ngIfand*ngFor:
- Under the hood, Angular turns these directives into
<ng-template>to control element insertion.
- Dynamic use through
ngTemplateOutlet:
html
<ng-container *ngTemplateOutlet="tpl"></ng-container>- Inserts the template's content at the specified location.
- Context variables:
html
<ng-template #tpl let-user>
<p>{{ user.name }}</p>
</ng-template>
<ng-container *ngTemplateOutlet="tpl; context: { $implicit: currentUser }"></ng-container>- Allows passing data into the template through local variables (
let-user), including$implicit.
In other words, <ng-template> is an invisible container for markup that Angular can create and insert dynamically depending on conditions or data.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.