javascript / expert
Snippet
Hydration-Safe DOM Interactions with afterNextRender
In Angular applications with SSR and Hydration enabled, direct DOM access must be deferred until the client-side stabilization. The `afterNextRender` hook ensures code only runs on the browser, preventing mismatch errors and ensuring that `viewChild` elements are fully instantiated before use.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { Component, ElementRef, viewChild, afterNextRender } from '@angular/core';@Component({standalone: true,template: `<canvas #graphCanvas></canvas>`})export class ChartComponent {canvas = viewChild<ElementRef<HTMLCanvasElement>>('graphCanvas');constructor() {afterNextRender(() => {const ctx = this.canvas()?.nativeElement.getContext('2d');if (ctx) this.renderComplexVisualization(ctx);});}private renderComplexVisualization(ctx: CanvasRenderingContext2D) {// Client-side only rendering logic involving the DOM}}
angular
Breakdown
1
afterNextRender(() => {
Registers a callback to be executed once the entire application has been rendered on the client.
2
const ctx = this.canvas()?.nativeElement.getContext('2d');
Safely accesses the native element of a signal-based viewChild after hydration stabilization.