Sub topic 10
Lazy and repeated content with ng-template
This chapter assumes you know how ng-content, select slots and content queries work, as covered in the earlier chapters. It also assumes you can write a standalone component with signal inputs. Here you will learn when plain projection is the wrong tool and how ng-template with ngTemplateOutlet handles those cases.
Where ng-content falls short
ng-content projects nodes that the parent has already created. That causes two problems:
- No laziness. The parent creates projected components and directives when it renders, whether or not the child shows them. Wrapping
<ng-content />in an@ifhides the nodes. It does not stop the parent from constructing them. - No repetition and no data. Projected nodes appear in one place. The child cannot render them once per item, and it cannot pass values into them.
An ng-template fixes both problems. It is a blueprint that Angular does not render by itself. The parent writes the blueprint, and the child decides when to create views from it, how many to create, and what data each view receives.
| Need | `ng-content` | `ng-template` + `ngTemplateOutlet` |
|---|---|---|
| Show static content in one place | Best fit | Works, but more code |
| Create content only when needed | No, content is created eagerly | Yes |
| Render the same content several times | No | Yes |
| Pass data from child to the content | No | Yes, through a context object |
| Parent's bindings resolve in the parent | Yes | Yes |
A template the child can instantiate
The child needs three things: a way to find the template, a place to render it, and a condition. The LazyBoxComponent below has all three.
import { Component, TemplateRef, contentChild, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
@Component({
selector: 'app-lazy-box',
imports: [NgTemplateOutlet],
template: `
@if (open()) {
<ng-container [ngTemplateOutlet]="body()" />
}
`,
})
export class LazyBoxComponent {
open = input(false);
body = contentChild.required(TemplateRef);
}contentChild.required(TemplateRef) finds the first ng-template projected into the component. ngTemplateOutlet creates an embedded view from it at the position of the ng-container. The ng-container adds no element to the DOM.
The parent supplies a template instead of plain content:
import { Component, signal } from '@angular/core';
import { LazyBoxComponent } from './lazy-box.component';
@Component({
selector: 'app-heavy-widget',
template: `<p>Heavy widget is running</p>`,
})
export class HeavyWidgetComponent {
constructor() {
console.log('HeavyWidgetComponent created');
}
}
@Component({
selector: 'app-demo',
imports: [LazyBoxComponent, HeavyWidgetComponent],
template: `
<button (click)="isOpen.set(!isOpen())">Toggle</button>
<app-lazy-box [open]="isOpen()">
<ng-template>
<app-heavy-widget />
</ng-template>
</app-lazy-box>
`,
})
export class DemoComponent {
isOpen = signal(false);
}When the page loads, the console stays quiet. HeavyWidgetComponent is not constructed until the first click on the button. A second click destroys the widget, and a third click builds a new instance. Any state inside the widget is lost each time.
If you replace the ng-template with direct content and put <ng-content /> inside the @if, the console logs the message at page load. The parent creates the widget regardless of the child's condition.
The template still belongs to the parent
An ng-template is compiled as part of the parent's template, so its expressions resolve against the parent's component class. The child's open input is not visible inside it. The parent's isOpen signal is visible. This matches the ownership rule for projected content, with one difference: Angular creates the views when the child asks for them, not when the parent renders.
Change detection follows the declaration, too. Angular checks an embedded view with the view that declared it. For ordinary use this means bindings in the template update with the parent's data, even though the DOM sits inside the child.
Repeating content with a context
The child can instantiate a template many times and hand each instance its own data. This is how list, table and select components let the consumer control the markup of each row.
import { Component, TemplateRef, contentChild, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
export interface RowContext {
$implicit: string;
index: number;
}
@Component({
selector: 'app-item-list',
imports: [NgTemplateOutlet],
template: `
<ul>
@for (item of items(); track $index; let i = $index) {
<li>
<ng-container
[ngTemplateOutlet]="rowTemplate()"
[ngTemplateOutletContext]="{ $implicit: item, index: i }"
/>
</li>
}
</ul>
`,
})
export class ItemListComponent {
items = input.required<string[]>();
rowTemplate = contentChild.required<TemplateRef<RowContext>>('row');
}Two things are new here. The query uses the template reference variable 'row' instead of a type, so the consumer must write #row on the template. The context object carries the data.
The parent reads the context with let- variables:
import { Component } from '@angular/core';
import { ItemListComponent } from './item-list.component';
@Component({
selector: 'app-fruit-page',
imports: [ItemListComponent],
template: `
<app-item-list [items]="fruits">
<ng-template #row let-fruit let-i="index">
<strong>{{ i + 1 }}.</strong> {{ fruit }}
</ng-template>
</app-item-list>
`,
})
export class FruitPageComponent {
fruits = ['Apple', 'Banana', 'Cherry'];
}The context works like this:
let-fruitwith no value binds the$implicitproperty of the context.let-i="index"binds theindexproperty to a variable namedi.- Each embedded view gets its own context, so every row sees its own
fruitandi.
The output is a list that reads "1. Apple", "2. Banana" and "3. Cherry". The child owns the loop and the <ul>. The parent owns the look of each row.
Changing a context object later is possible: when the object you pass in the binding changes, Angular updates the existing views. A fresh object literal in the template, as above, is fine because Angular compares its properties.
Several templates in one component
A component often needs more than one template, such as a header and a row. Give each its own reference variable and query each by name.
import { Component, TemplateRef, contentChild, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
@Component({
selector: 'app-grid',
imports: [NgTemplateOutlet],
template: `
<div class="head">
@if (headTemplate(); as head) {
<ng-container [ngTemplateOutlet]="head" />
} @else {
Default header
}
</div>
@for (row of rows(); track row) {
<div class="row">
<ng-container
[ngTemplateOutlet]="cellTemplate()"
[ngTemplateOutletContext]="{ $implicit: row }"
/>
</div>
}
`,
})
export class GridComponent {
rows = input.required<string[]>();
headTemplate = contentChild<TemplateRef<unknown>>('head');
cellTemplate = contentChild.required<TemplateRef<{ $implicit: string }>>('cell');
}The optional contentChild('head') returns undefined when the parent leaves the template out. The @else branch then plays the role that fallback content plays for ng-content. Required queries suit templates the component cannot work without.
Choosing between the two
Use plain ng-content when the content is static, always shown, and does not need data from the child. A card, a panel and a dialog shell are typical cases. The code is shorter, and the parent writes ordinary markup.
Use ng-template when at least one of these holds:
- The content is expensive and should exist only while visible, as in tabs, accordions and dropdown panels.
- The child renders the content several times, as in lists and tables.
- The child must pass data into the content.
- The child must create and destroy the content repeatedly, for example on each open and close.
A hybrid design is common. A component can accept simple content through ng-content and also offer an optional template for advanced cases. The GridComponent header above follows that idea.
Pitfalls
- Missing template.
contentChild.requiredthrows if no matching template is projected. Read the signal only after content initialisation. In templates andcomputedoreffectcode this is the normal case, but do not read it in the constructor. - Wrong query target.
contentChild(TemplateRef)returns the first template only. If a component takes two templates, query by reference variable so the order in the parent does not matter. - Lost state. Closing the lazy box destroys the embedded view and everything in it. Keep state that must survive in a service or in the parent.
- Forgotten import. In a standalone component you must list
NgTemplateOutletinimports. Without it, the[ngTemplateOutlet]binding fails to compile, becauseng-containerhas no such property. - Untyped context. A plain
TemplateRef<unknown>gives no type checking forlet-variables in the parent. To get checking, add a small directive with a staticngTemplateContextGuardmethod and put it on theng-template. For many components, documenting the context shape is enough. - Outlet with no template. Passing
nullorundefinedtongTemplateOutletrenders nothing and raises no error. This helps with optional templates, but a typo in a reference variable name can hide behind it.
Exercise
A tabs component wraps its panel content in @if (active()) { <ng-content /> }. The panel contains a component that fetches data in its constructor. All tabs fetch data at page load. Why, and how do you fix it?
Show answer
The parent creates projected content when it renders, so the @if only hides nodes that already exist. Change the tab so the parent supplies an <ng-template>, query it with contentChild.required(TemplateRef), and render it with [ngTemplateOutlet] inside the @if. The fetching component is then constructed only when the tab becomes active.
Exercise
You write <ng-template #row let-name let-n="index">{{ n }}: {{ name }}</ng-template> in a parent, and the child's outlet uses the context { $implicit: 'Ada', index: 4 }. What does each row display, and what happens if the child sets the context to { $implicit: 'Ada' } only?
Show answer
With the full context the row shows "4: Ada". let-name takes $implicit, and let-n="index" takes index. With only $implicit, n is undefined, so the row shows ": Ada". Angular raises no error for a missing context property.