
Hydration Isn't Re-rendering: How Angular Reuses Server HTML
- كاتب موثّق
- Angular 22
محتويات المقال
ngOnInit with createElement() and insertBefore(). Someone puts ngSkipHydration on the root component to silence the error, and it works: no more NG0500. But now the page flickers once as it finishes loading, because that attribute brought back exactly what the team thought SSR always did: rebuild the page from scratch.
The common misconception
console.log in a constructor shows up once in the server's terminal and again in the browser console. And the belief describes a real mode of Angular SSR. The hydration guide says that without hydration enabled, a server-rendered Angular app "will destroy and re-render the application's DOM", which may cause a visible flicker. So the half-truth is this: your component code runs twice, but the DOM doesn't have to be built twice.
What actually happens
The server sends HTML and a map of it
@if and @for blocks. The page can also carry data, like HttpClient responses the server already fetched, so the browser doesn't have to ask again.
The browser runs your components but adopts the DOM
ngOnInit run, signals and inputs get their values. The difference is in the step that would normally create elements. In the guide's words, Angular "tries to match existing DOM elements to the application's structure at runtime and reuses DOM nodes when possible". It claims the server's <div> instead of making a new one, and attaches listeners to it. After hydration, a cleanup step removes the nodes nobody claimed.
Until then, the page is a picture
provideClientHydration() enables by default, so an early click on "Add to cart" isn't lost.
The contract: the same DOM on both sides
Direct DOM manipulation with native APIs: createElement(),appendChild(), settinginnerHTML, moving nodes.Invalid HTML the browser repairs while parsing: a <table>without<tbody>, a<div>inside a<p>, an<a>inside another<a>.Templates that branch on the platform, such as @ifwithisPlatformBrowser, so the browser renders a different structure than the server did.
import { Component, DOCUMENT, ElementRef, inject, input, OnInit,} from '@angular/core';@Component({ selector: 'app-price', template: `<div class="price">{{ amount() }}</div>`,})export class Price implements OnInit { readonly amount = input.required<string>(); readonly onSale = input(false); private readonly host = inject(ElementRef<HTMLElement>).nativeElement; private readonly doc = inject(DOCUMENT); ngOnInit() { if (!this.onSale()) return; // Angular has no record of this node, so the DOM no longer // matches what the server annotated: hydration fails (NG0500) const badge = this.doc.createElement('span'); badge.textContent = 'Sale'; this.host.insertBefore(badge, this.host.firstChild); }}import { Component, input } from '@angular/core';@Component({ selector: 'app-price', template: ` @if (onSale()) { <span class="badge">Sale</span> } <div class="price">{{ amount() }}</div> `,})export class Price { // Same inputs on the server and in the browser, so the same // DOM: hydration claims the <span> instead of rebuilding it readonly amount = input.required<string>(); readonly onSale = input(false);}@if branch, the browser reaches the same branch with the same inputs, and hydration claims the <span> like any other node. When you truly need imperative DOM work, such as a chart library, run it in afterNextRender(), which runs only in the browser after rendering. The guide gives the same advice for third-party scripts that touch the DOM.
ngSkipHydration brings the old behavior back
ngSkipHydration on a component's host makes Angular skip hydrating that component and all its children. The guide says such a component "will destroy and re-render itself", and that putting it on the root component effectively disables hydration for the whole app. It's a last-resort workaround, and the guide treats components that need it as bugs to fix.
ngSkipHydration is a fix |
How to apply it in your project
Confirm hydration is on Projects created with ng new --ssrorng add @angular/ssralready callprovideClientHydration(). In a custom setup, make sure it's in both the browser and the server providers.Move DOM edits into templates Search components for createElement,appendChild,insertBeforeandinnerHTML. Turn each into template markup, or move it intoafterNextRender()when a library must own that DOM.Validate your HTML Add an explicit <tbody>to every table, and look for block elements inside<p>and links inside links.Treat every ngSkipHydration as a bug List each use, note the component it hides, and remove it once that component stops editing the DOM. Never put it on the root component.
Key takeaways
Hydration reuses the server's DOM nodes; without it, Angular destroys and re-renders the page. Your component code still runs in the browser. Only the DOM creation is skipped. Listeners attach when hydration completes; event replay, on by default in Angular 22, keeps early clicks. The server and the browser must produce the same DOM, so edit it through templates, not native APIs. ngSkipHydrationis a temporary escape hatch that brings the flicker back for that subtree.
التعليقات (0)