Sub topic 7
Working with projected content: the AfterContent hooks
This chapter assumes you know the constructor, ngOnInit and ngOnChanges, and can use <ng-content> for basic content projection. You should also be comfortable reading RxJS observables. The chapter covers ngAfterContentInit and ngAfterContentChecked, the two hooks that tell a component its projected content is ready.
What "content" means
Content is the markup a parent writes between a component's opening and closing tags. The component decides where it appears with <ng-content>.
<app-tabs>
<app-tab label="Profile">Profile details</app-tab>
<app-tab label="Billing">Billing details</app-tab>
</app-tabs>The two app-tab elements are the content of app-tabs. The app-tabs template is its view. Angular keeps the two apart, and different queries and hooks apply to each:
| Concept | Declared in | Query decorator | Hook |
|---|---|---|---|
| Content | The parent's template, between the tags | `@ContentChild`, `@ContentChildren` | `ngAfterContentInit`, `ngAfterContentChecked` |
| View | The component's own template | `@ViewChild`, `@ViewChildren` | `ngAfterViewInit`, `ngAfterViewChecked` |
A component cannot see its own template through a content query, and it cannot see projected elements through a view query.
When the hooks run
Both hooks come after ngOnChanges, ngOnInit and ngDoCheck, and before the view hooks.
ngAfterContentInitruns once. Angular has initialized the projected content, and content queries are populated.ngAfterContentCheckedruns afterngAfterContentInitand again after every later check of the projected content. On later checks it runs right afterngDoCheck.
Neither hook is tied to the component's own template. Angular has not yet rendered the component's view when ngAfterContentInit runs. Use the AfterView hooks for work that needs it.
Querying content
A content query collects directives or components that the parent declared inside the host element.
@ContentChild(Type)returns the first match, orundefined.@ContentChildren(Type)returns aQueryList<Type>. This is an iterable collection with achangesobservable that emits whenever the set of matches changes.
By default @ContentChildren matches only direct children of the host element, with descendants: false. If your tabs sit inside a wrapper <div>, set { descendants: true }. A content query also matches elements the component never projects. If the template has no <ng-content>, the child components are still created and still show up in the query. They are just not attached to the DOM.
Worked example: tabs that read their children
TabComponent only carries a label. TabsComponent reads all projected tabs and builds a header from their labels.
import {
AfterContentInit,
Component,
ContentChildren,
Input,
OnDestroy,
QueryList,
} from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-tab',
standalone: true,
template: `<ng-content />`,
})
export class TabComponent {
@Input() label = '';
}
@Component({
selector: 'app-tabs',
standalone: true,
template: `
<nav>
@for (title of titles; track $index) {
<span class="tab-title">{{ title }}</span>
}
</nav>
<ng-content />
`,
})
export class TabsComponent implements AfterContentInit, OnDestroy {
@ContentChildren(TabComponent) tabs!: QueryList<TabComponent>;
titles: string[] = [];
private changesSub?: Subscription;
ngAfterContentInit(): void {
this.refreshTitles();
this.changesSub = this.tabs.changes.subscribe(() => this.refreshTitles());
}
private refreshTitles(): void {
this.titles = this.tabs.map((tab) => tab.label);
}
ngOnDestroy(): void {
this.changesSub?.unsubscribe();
}
}Several details in this example matter:
this.tabsisundefinedin the constructor and inngOnInit, because the query is dynamic. Reading it inngAfterContentInitis safe.- The component writes to its own field,
titles, and not to the child tabs. Its own view has not been checked yet, so the template reads the new value in the same pass with no error. tabs.changescovers tabs that are added or removed later, for example with@ifor@forin the parent. It does not emit for the first set of tabs, so the code reads that set once directly.- The subscription is released in
ngOnDestroy. AQueryListis destroyed with the component, so in practice this particular subscription would not leak, but the habit is worth keeping for observables that outlive the component.
Usage in a parent:
import { Component } from '@angular/core';
import { TabComponent, TabsComponent } from './tabs';
@Component({
selector: 'app-root',
standalone: true,
imports: [TabsComponent, TabComponent],
template: `
<app-tabs>
<app-tab label="Profile">Profile details</app-tab>
<app-tab label="Billing">Billing details</app-tab>
</app-tabs>
`,
})
export class AppComponent {}Static and dynamic queries
A content query is dynamic by default and resolves just before ngAfterContentInit. If the matched element is not inside an <ng-template> or a control-flow block such as @if, you can set { static: true }. The result is then available in ngOnInit.
@ContentChild(TabComponent, { static: true }) firstTab?: TabComponent;A static query is never updated afterwards. Prefer the default unless you need the value early. A static query that matches nothing at creation time stays empty even if matching content appears later.
Signal queries
In recent Angular versions, contentChild() and contentChildren() return signals. They give the same data without the decorator and without a ! assertion.
import { Component, computed, contentChildren } from '@angular/core';
import { TabComponent } from './tabs';
@Component({
selector: 'app-tab-count',
standalone: true,
template: `<p>{{ count() }} tabs</p><ng-content />`,
})
export class TabCountComponent {
tabs = contentChildren(TabComponent);
count = computed(() => this.tabs().length);
}The signal updates when the set of matches changes, so you often do not need ngAfterContentInit at all.
ngAfterContentChecked
ngAfterContentChecked runs on every change detection pass, like ngDoCheck. Use it when something must stay in sync with projected content that can change without a new query result. An example is a child whose own properties are mutated by the parent. Two rules follow from how often it runs:
- Keep it cheap. Compare and exit early.
- Do not change state that the already-checked parts of the tree have bound to.
import { AfterContentChecked, Component, ContentChild } from '@angular/core';
import { TabComponent } from './tabs';
@Component({
selector: 'app-first-label',
standalone: true,
template: `<h3>{{ heading }}</h3><ng-content />`,
})
export class FirstLabelComponent implements AfterContentChecked {
@ContentChild(TabComponent) first?: TabComponent;
heading = '';
ngAfterContentChecked(): void {
const next = this.first?.label ?? '';
if (next !== this.heading) {
this.heading = next;
}
}
}The guard (next !== this.heading) avoids needless writes. The write targets the component's own field, which its template has not read yet in this pass.
Common errors
- Reading a content query in the constructor or
ngOnInit. The value isundefinedunless the query is static. Move the code tongAfterContentInit. - Querying your own template with a content query. It returns nothing. Use
@ViewChildfor elements in your own template. - Missing nested matches. With the default
descendants: false, a tab wrapped in another element is skipped. ExpressionChangedAfterItHasBeenChecked. This appears when a content hook changes a value that an already-checked binding displays, such as a property of a projected child or of an ancestor. In development mode Angular runs a second pass and the values differ. Change your own state, not state that was bound earlier in the pass.- Heavy work in
ngAfterContentChecked. It runs far more often than you expect. Compare cheap values, or useQueryList.changesor signals instead.
Exercise
A TabsComponent declares @ContentChildren(TabComponent) tabs!: QueryList<TabComponent> and logs this.tabs.length in ngOnInit. What happens, and where should the code move? Also, why might a tab wrapped in <div><app-tab /></div> be missing from the list?
Show answer
this.tabs is still undefined in ngOnInit because the query is dynamic, so reading .length throws a TypeError. Move the code to ngAfterContentInit, where the query is populated. The wrapped tab is missing because @ContentChildren defaults to descendants: false and matches only direct children of the host element. Use @ContentChildren(TabComponent, { descendants: true }) to include it.