Sub topic 17
Reusable Fragments with ng-template and ngTemplateOutlet
This chapter assumes you already know component inputs, @if and @for, template reference variables, and contentChild queries from earlier chapters. All examples use standalone components (Angular 19+) with signal-based APIs.
Sometimes a piece of markup has to appear in several places, or a parent needs to decide how a child renders part of its UI. Extracting a whole component for that can be too much. Angular offers a lighter tool for this: a template fragment that you declare once and render wherever you need it, with its own data each time.
The three building blocks
| Construct | What it is | Renders anything by itself? |
|---|---|---|
| `<ng-template>` | A declaration of a markup fragment. Angular compiles it into a `TemplateRef` object. | No |
| `<ng-container>` | A grouping element that adds no DOM node. You often use it as the host for a directive. | Only its children |
| `NgTemplateOutlet` | A directive from `@angular/common` that creates an embedded view from a `TemplateRef` at a given location. | Yes, it renders the given template |
An embedded view is a live instance of a template. It has its own bindings and takes part in change detection like any other view. A single TemplateRef can produce any number of embedded views.
Declaring and stamping a fragment
The component below declares a row template once and renders it for every item. The fragment receives data through a context object.
import { Component } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
interface Product {
name: string;
price: number;
}
@Component({
selector: 'app-price-list',
imports: [NgTemplateOutlet],
template: `
<ng-template #priceRow let-product let-onSale="onSale">
<li [class.sale]="onSale">{{ product.name }}: {{ product.price }}</li>
</ng-template>
<h3>Fruit</h3>
<ul>
@for (p of fruit; track p.name) {
<ng-container
*ngTemplateOutlet="priceRow; context: { $implicit: p, onSale: p.price < 2 }">
</ng-container>
}
</ul>
<h3>Vegetables</h3>
<ul>
@for (p of vegetables; track p.name) {
<ng-container
[ngTemplateOutlet]="priceRow"
[ngTemplateOutletContext]="{ $implicit: p, onSale: false }">
</ng-container>
}
</ul>
`,
styles: `.sale { color: green; font-weight: bold; }`
})
export class PriceListComponent {
fruit: Product[] = [
{ name: 'Apple', price: 1.5 },
{ name: 'Mango', price: 3 }
];
vegetables: Product[] = [{ name: 'Carrot', price: 0.8 }];
}The context has these parts:
let-productwith no value binds to the context's$implicitproperty.let-onSale="onSale"binds the local variableonSaleto the context property namedonSale.- The two outlet forms do the same thing. The microsyntax
*ngTemplateOutlet="tpl; context: ctx"is a shorthand for the[ngTemplateOutlet]and[ngTemplateOutletContext]input pair.
ng-container is the usual outlet host because it leaves no wrapper element. In this example the <li> stays a direct child of the <ul>.
Letting the parent supply the template
The more useful pattern is to let a consumer customize how a reusable component renders. The list component below owns the looping and layout. The parent decides what each row looks like by projecting an <ng-template>, which the list picks up with a contentChild query.
import { Component, TemplateRef, contentChild, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
export interface RowContext {
$implicit: string;
index: number;
}
@Component({
selector: 'app-fancy-list',
imports: [NgTemplateOutlet],
template: `
<ul>
@for (item of items(); track item; let i = $index) {
<li>
@if (rowTemplate(); as tpl) {
<ng-container
*ngTemplateOutlet="tpl; context: { $implicit: item, index: i }">
</ng-container>
} @else {
{{ item }}
}
</li>
}
</ul>
`
})
export class FancyListComponent {
items = input.required<string[]>();
rowTemplate = contentChild<TemplateRef<RowContext>>(TemplateRef);
}
@Component({
selector: 'app-team',
imports: [FancyListComponent],
template: `
<app-fancy-list [items]="names">
<ng-template let-name let-i="index">
<strong>{{ i + 1 }}.</strong> {{ name }} ({{ team }})
</ng-template>
</app-fancy-list>
<app-fancy-list [items]="names" />
`
})
export class TeamComponent {
names = ['Ada', 'Grace', 'Linus'];
team = 'Platform';
}The second <app-fancy-list> projects no template, so it falls back to plain text through @else.
The row template reads team, a property of TeamComponent, even though it renders inside FancyListComponent. This is the key rule of template fragments. Bindings resolve in the scope where the template is declared, not where it is rendered. The context object only adds extra variables on top of that scope.
You can also pass a template as an ordinary input, for example rowTemplate = input<TemplateRef<RowContext>>(). The parent then writes <app-fancy-list [rowTemplate]="myRow" /> and declares <ng-template #myRow> somewhere in its own template. Choose between the two approaches like this:
| Approach | Good for | Drawback |
|---|---|---|
| Projected template + `contentChild` | A natural, declarative API with the template written inline | Only one template per query unless you use selectors or `contentChildren` |
| Template as an `input()` | Several named templates, or templates chosen dynamically | The parent has to declare the template separately and wire it up |
Typing the context
With strictTemplates, the variables in a projected template such as let-name are typed any by default, because the compiler cannot connect the consumer's <ng-template> to RowContext. Typing TemplateRef<RowContext> documents the contract and checks the outlet side. To get type checking on the consumer side as well, add a small directive that declares a static ngTemplateContextGuard. That technique is beyond this chapter. For most internal components, the typed TemplateRef is enough.
How it works internally
*ngIf, *ngFor, and the other legacy structural directives desugar to <ng-template> plus a directive that calls ViewContainerRef.createEmbeddedView(templateRef, context). NgTemplateOutlet does the same thing. It is a thin directive that:
- Clears its view container when the template input changes.
- Creates one embedded view from the new
TemplateRefwith the given context. - Updates that view's context in place when only the context changes, as long as the set of property names stays the same.
Because of step 3, the object literal you pass as the context does not destroy and rebuild the view on every change detection pass. Angular memoizes literal expressions in templates, and the outlet patches the existing context. Switching to a different TemplateRef does destroy the old view, along with any state inside it such as form input values or child component instances.
Common errors and gotchas
- Forgetting the import. If
NgTemplateOutletis missing fromimports, the compiler reports "Can't bind to 'ngTemplateOutlet' since it isn't a known property of 'ng-container'". - Misnamed context keys.
let-i="idx"when the context providesindexgivesundefinedwithout any error. Keep the context shape in an interface. - Confusing
$implicitwith a named key.let-xreads$implicit.let-x="x"reads the property namedx. - Querying too early. A
viewChildorcontentChildsignal for a template readsundefineduntil the view or content has been initialized. Read it in a template expression, acomputed, orafterNextRender, not in the constructor. - Assuming the outlet scope. A projected template cannot see the child component's fields unless the child passes them through the context.
- Overusing fragments. If a fragment needs its own inputs, logic, and styles, make it a component instead. Templates suit small, presentation-only variations.
Exercise
In TeamComponent, the row template displays {{ team }}. FancyListComponent also gets a field team = 'List'. Which value does the row show, and why?
Show answer
It shows 'Platform'. Template bindings resolve in the lexical scope where the <ng-template> is declared, which is TeamComponent. The rendering component only contributes values that it passes explicitly through the context object.
Exercise
Change FancyListComponent so the projected template can also show whether a row is the last one, and write the matching ng-template in the parent that shows "(last)" after the final name.
Show answer
Add last: boolean to RowContext. In the @for, add let l = $last and pass context: { $implicit: item, index: i, last: l }. In the parent, write <ng-template let-name let-i="index" let-last="last">{{ i + 1 }}. {{ name }} @if (last) { (last) }</ng-template>.
Exercise
You change the outlet so it alternates between two different TemplateRef objects each time a button is clicked. Each template contains a text input. What happens to text the user has typed?
Show answer
The text is lost. When the template input of NgTemplateOutlet changes, the directive destroys the existing embedded view and creates a new one, so all DOM and component state inside the old view is discarded. Changing only the context values would keep the view and its state.