Sub topic 13
Render hooks for DOM work after rendering
This chapter assumes you know the component hooks from the earlier chapters (ngOnInit, ngAfterViewInit, ngOnDestroy), basic change detection, and Angular signals at the level of signal() and .set(). It uses the Angular 19+ API. Version differences are noted where they matter.
The problem render hooks solve
ngAfterViewInit tells you that the component's view has been created. It does not tell you that the browser has laid the page out, and it also runs during server-side rendering (SSR), where no real DOM exists. Code that measures elements, starts a charting library, or reads scroll positions often needs two guarantees that the classic hooks do not give:
- Angular has finished writing its updates to the DOM.
- The code runs only in a browser.
Render hooks give you both. They are functions you register, not methods you implement on the class. Angular calls them after it has finished rendering the application.
| Function | When the callback runs | Typical use |
|---|---|---|
| `afterNextRender` | Once, after the next render completes | One-time setup: initialize a library, measure once |
| `afterRender` (renamed `afterEveryRender` in Angular 20) | After every render | Keep external state in sync with the DOM |
Neither callback runs on the server. This is the main reason to prefer them over ngAfterViewInit for DOM access.
A first example: measuring after render
import { Component, ElementRef, afterNextRender, signal, viewChild } from '@angular/core';
@Component({
selector: 'app-measure',
standalone: true,
template: `
<div #panel>Content to measure</div>
<p>Height: {{ height() }}px</p>
`,
})
export class MeasureComponent {
private readonly panel = viewChild.required<ElementRef<HTMLElement>>('panel');
readonly height = signal(0);
constructor() {
afterNextRender({
write: () => {
const el = this.panel().nativeElement;
el.style.minHeight = '120px';
return el;
},
read: (el) => {
this.height.set(el.getBoundingClientRect().height);
},
});
}
}The call sits in the constructor because render hooks must be registered in an injection context. That means the constructor, a field initializer, or a function you run with runInInjectionContext. The view query panel() is safe to read inside the callback because the view has been rendered by then. Reading it in the constructor itself would fail.
The callback is written as an object with write and read phases. The next section explains why.
Phases: keeping reads and writes apart
Browsers do layout work lazily. If you write a style and then immediately read a layout value such as getBoundingClientRect(), the browser must recalculate layout on the spot. Do this for many elements in a row and you get repeated forced layouts, called layout thrashing.
Angular avoids this by running all callbacks of one phase before any callback of the next. Every component that registers a hook is sorted into the same four phases:
earlyRead: read the DOM before anything is written. Rarely needed.write: change the DOM, such as styles, attributes and scroll position.mixedReadWrite: read and write in one callback. This is the default for the plain function form, and Angular recommends avoiding it.read: read layout values after all writes are done.
Each phase passes its return value to the next phase that you define. In the example above, write returns the element and read receives it as el. The types flow through, so TypeScript checks the hand-off.
If you pass a plain function instead of an object, it runs in the mixedReadWrite phase:
afterNextRender(() => {
console.log('Rendered in the browser; safe to touch the DOM');
});That is fine for small one-off tasks. Use the phase object when several components read and write layout, so they do not interleave and force repeated layouts.
Running on every render
afterNextRender fires once. To react after each render, use the repeating version. In Angular 17 to 19 it is called afterRender. Angular 20 renamed it afterEveryRender, and the example below uses the new name.
import { Component, ElementRef, afterEveryRender, input, viewChild } from '@angular/core';
@Component({
selector: 'app-log-view',
standalone: true,
template: `
<div #scroller class="scroller" style="height: 200px; overflow: auto">
@for (line of lines(); track $index) {
<div>{{ line }}</div>
}
</div>
`,
})
export class LogViewComponent {
readonly lines = input<string[]>([]);
private readonly scroller = viewChild.required<ElementRef<HTMLElement>>('scroller');
constructor() {
afterEveryRender({
write: () => {
const el = this.scroller().nativeElement;
el.scrollTop = el.scrollHeight;
},
});
}
}When new log lines arrive and Angular renders them, the callback scrolls to the bottom. A callback like this runs after every change detection pass for the whole application, not only passes caused by this component. Keep it cheap and check whether you need to do anything. A common pattern is to compare a stored value with the current one and return early.
Registering outside the constructor
Sometimes you only know you need DOM work later, for example after a user action. Inject an Injector and pass it in the options. Hold on to the returned reference so you can cancel the hook:
import { Component, Injector, afterNextRender, inject } from '@angular/core';
@Component({
selector: 'app-lazy-widget',
standalone: true,
template: `<button (click)="open()">Open</button><div id="widget-host"></div>`,
})
export class LazyWidgetComponent {
private readonly injector = inject(Injector);
open(): void {
const ref = afterNextRender(
() => {
const host = document.getElementById('widget-host');
if (host) {
host.textContent = 'Widget ready';
}
},
{ injector: this.injector },
);
// Call ref.destroy() if the callback becomes unnecessary before it runs.
}
}Hooks registered inside a component's injection context are cleaned up automatically when the component is destroyed. A hook registered with a custom injector follows the lifetime of that injector.
Behavior to remember
- SSR and prerendering: callbacks are skipped on the server. Do not use them for anything the server-rendered HTML needs, because that content would be missing.
- Signals set inside a hook: setting a signal that the template reads schedules another render. With
afterEveryRender, that can loop forever if the callback always changes something. Guard the update. - No
ExpressionChangederrors from the callback itself: render hooks run after the checked pass, so they sit outside the dev-mode check that raisesExpressionChangedAfterItHasBeenChecked. That is also why they are the right place for work that would otherwise cause it. - Hooks are not an event system: they say that rendering finished, not which input changed. To react to a specific change, use
ngOnChangesor aneffect.
Choosing between hooks
| Need | Use |
|---|---|
| Run once, view exists, no DOM measurements needed | `ngAfterViewInit` |
| Run once, needs real layout or a browser-only API | `afterNextRender` |
| Re-measure or re-sync after updates | `afterEveryRender` (`afterRender` before Angular 20) |
| Respond to one specific input | `ngOnChanges` or a signal `effect` |
Exercise
A component calls document.querySelector('.banner')!.getBoundingClientRect() in ngAfterViewInit. The app now uses SSR and the page crashes on the server. Rewrite the idea using a render hook, and say which phase the measurement belongs in and why.
Show answer
Register afterNextRender({ read: () => { const banner = document.querySelector('.banner'); if (banner) { this.bannerHeight.set(banner.getBoundingClientRect().height); } } }) in the constructor. afterNextRender is skipped on the server, so document is never touched there. The measurement belongs in the read phase because it only reads layout. Angular runs all write callbacks before any read callbacks, so the value reflects the final DOM and no forced layout happens between writes.
Exercise
You use afterEveryRender and, inside the callback, always call this.count.update(c => c + 1), where the template displays count(). What goes wrong, and how do you fix it?
Show answer
Changing the signal marks the view dirty and schedules another render. That render runs the callback again, which changes the signal again, so rendering repeats without end. Fix it by only updating when needed (compare with the previous value and return early), or by moving the logic to an event handler or effect if it does not depend on DOM state.