Sub topic 17
Reusable Fragments with ng-template and ngTemplateOutlet
This chapter assumes you know control flow blocks, template reference variables, content projection, and the :host selector from earlier chapters. It covers two tools. The first is a way to define a piece of markup once and render it in several places. The second lets a component set classes, attributes, and listeners on its own host element.
Defining a fragment with ng-template
An <ng-template> holds markup that Angular does not render on its own. Think of it as a blueprint: nothing appears in the DOM until something asks for it. You name the blueprint with a template reference variable such as #row. You can then stamp it out with the NgTemplateOutlet directive.
<ng-container> is a grouping element that adds no DOM node of its own. It is a convenient place to attach the outlet.
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 #row let-item let-pos="position">
<li>{{ pos }}. {{ item.name }}: {{ item.price }}</li>
</ng-template>
<h3>Featured</h3>
<ul>
<ng-container
[ngTemplateOutlet]="row"
[ngTemplateOutletContext]="{ $implicit: featured, position: 1 }">
</ng-container>
</ul>
<h3>All products</h3>
<ul>
@for (p of products; track p.name; let i = $index) {
<ng-container
[ngTemplateOutlet]="row"
[ngTemplateOutletContext]="{ $implicit: p, position: i + 1 }">
</ng-container>
}
</ul>
`
})
export class PriceListComponent {
products: Product[] = [
{ name: 'Pen', price: 2 },
{ name: 'Notebook', price: 5 }
];
featured = this.products[1];
}The context object passes data into the fragment:
| Context key | Template declaration | Meaning |
|---|---|---|
| `$implicit` | `let-item` | Default value, used when `let-` has no name on the right |
| `position` | `let-pos="position"` | Named value, mapped to a local variable |
Common errors
- Forgetting
NgTemplateOutletinimports. Angular then reports thatngTemplateOutletis not a known property ofng-container. - Expecting
<ng-template>to render by itself. It renders only through an outlet, a structural directive, or aViewContainerRef. - Misspelling a context key. When a key is misspelled, the local variable is
undefined, and in many setups this shows up as blank output with no error.
Binding to the host element
The host element is the tag that matches your selector, such as <app-badge>. Use the host property in @Component to bind to the host element. The keys follow template binding syntax.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<ng-content />`,
host: {
role: 'status',
'[class.active]': 'active()',
'[attr.aria-pressed]': 'active()',
'(click)': 'toggle()'
},
styles: `
:host { display: inline-block; padding: 0.25rem 0.5rem; cursor: pointer; }
:host(.active) { background: #cde; }
`
})
export class BadgeComponent {
active = signal(false);
toggle() {
this.active.update(a => !a);
}
}A plain key such as role sets a static attribute. A key in brackets is a property, class, attribute, or style binding. A key in parentheses is an event listener. You will also see the older decorator forms @HostBinding('class.active') and @HostListener('click'). Angular now recommends the host object.
Exercise
A template is declared as <ng-template #greet let-name let-n="count">Hi {{ name }} ({{ n }})</ng-template>. Write an ng-container that renders it with name "Ada" and count 3.
Show answer
<ng-container [ngTemplateOutlet]="greet" [ngTemplateOutletContext]="{ $implicit: 'Ada', count: 3 }"></ng-container>. The component must also list NgTemplateOutlet in its imports.
Exercise
How do you make a component add the class disabled to its own host element whenever its disabled signal input is true?
Show answer
Add host: { '[class.disabled]': 'disabled()' } to the @Component metadata, where disabled = input(false).