Skip to main content

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

  1. 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 (via ngTemplateOutlet or a structural directive).
  1. Use with *ngIf and *ngFor:
  • Under the hood, Angular turns these directives into <ng-template> to control element insertion.
  1. Dynamic use through ngTemplateOutlet:
html
<ng-container *ngTemplateOutlet="tpl"></ng-container>
  • Inserts the template's content at the specified location.
  1. 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.