Sub topic 9
Skipping hydration for problem components
This chapter assumes you know how Angular hydration reuses server-rendered DOM, and that you can read a hydration mismatch error in the console. You should also be comfortable with standalone components and the platform checks from earlier chapters. By the end, you will know when to opt a component out of hydration, how to do it, and what it costs.
What skipping hydration does
Normally, Angular hydration walks the server-rendered DOM and attaches component instances, listeners, and bindings to the existing nodes. It does not rebuild them. This works only if the DOM the browser received has the same structure that Angular expects to produce on the client.
Some components break that assumption. Examples are:
- A third-party widget that rewrites its own DOM in its constructor or in a lifecycle hook.
- A component that calls
innerHTML,appendChild, orinsertBeforeon its own template nodes. - A component whose markup the HTML parser changes, so the DOM differs from the template.
For these, you can mark the component host element with the ngSkipHydration attribute. Angular then does the following for that component and everything inside it:
- It ignores the server-rendered DOM for that subtree.
- It removes the subtree's nodes and renders the component again from scratch in the browser.
- It treats the subtree as not hydrated, so none of the existing nodes are reused.
The rest of the page stays hydrated. The opt-out applies per component, not per application.
<app-legacy-widget ngSkipHydration />The server still renders app-legacy-widget into the HTML, so the user sees it before JavaScript loads. When the browser bootstraps, Angular discards that markup and builds it again. Expect a brief flicker or layout shift if the client output differs visually from the server output.
Three ways to apply it
You can set the opt-out in a template or on the component itself.
In a parent template
Put the attribute on the host element where the component is used. This is the form in the example above. It affects only that usage, so other places that use the same component stay hydrated.
In the component metadata
If a component should never hydrate, set the host attribute in its decorator. Every usage then opts out, and callers cannot forget the attribute.
import { Component } from '@angular/core';
@Component({
selector: 'app-legacy-widget',
host: { ngSkipHydration: 'true' },
template: `<div class="legacy-root"></div>`,
})
export class LegacyWidgetComponent {}Angular accepts the attribute with the value true in host metadata. In a template, the bare attribute is enough.
Choosing between them
| Where you set it | Scope | Use it when |
|---|---|---|
| Template host element | One usage | Only some usages are a problem, for example one page embeds the widget in a way that mutates the DOM. |
| `host` metadata | Every usage | The component itself manipulates the DOM unsafely, whatever the context. |
Limits of the attribute
There are rules you can trip over.
- It works only on component host elements. Putting
ngSkipHydrationon a plain<div>that is not a component host does nothing, and Angular logs an error in development mode. Wrap the content in a component if you need to opt it out. - It applies to the whole subtree. Every child component inside is also not hydrated, even if the children are well behaved.
- It cannot be bound. You cannot write
[ngSkipHydration]="flag". The decision is static, made at compile time. If you need a conditional opt-out, use two components or an@ifthat selects between a hydrated and a skipped usage. - The root component is a special case. Applying it to the root component disables hydration for the whole application. At that point you have SSR without hydration, and you lose the benefit of reusing the DOM.
A worked example
Suppose a legacy chart library draws into a container by calling appendChild on an element that Angular created. The component looks like this.
import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';
@Component({
selector: 'app-legacy-chart',
template: `<div #canvas class="chart"></div>`,
})
export class LegacyChartComponent {
private canvas = viewChild.required<ElementRef<HTMLDivElement>>('canvas');
constructor() {
afterNextRender(() => {
const el = document.createElement('span');
el.textContent = 'Chart drawn by legacy code';
this.canvas().nativeElement.appendChild(el);
});
}
}Here the DOM change happens after render in the browser, so the server output is a plain empty div. Hydration succeeds. The manipulation runs after Angular has finished matching nodes, and it does not conflict with anything.
Now change the component so the library mutates the DOM during construction, before hydration finishes matching. A common version of this is a library that replaces the template's markup using innerHTML as soon as it can see the element. Angular then finds a different structure from the one it expects and reports an error such as NG0500: During hydration Angular expected <div> but found <span>.
The fix with the least code is to opt out for this component.
<section class="dashboard">
<h2>Sales</h2>
<app-legacy-chart ngSkipHydration />
</section>The heading and section stay hydrated. Only the chart is thrown away and rebuilt in the browser.
Check the result by loading the page with the browser console open. The mismatch error should be gone. In development mode, Angular also prints hydration statistics. Look for the component being counted as skipped rather than hydrated.
Prefer fixing the cause when you can
Skipping hydration is a workaround. It has real costs:
- The server work for that subtree is wasted, since the browser throws the HTML away.
- The browser redoes the DOM creation, which costs time on slower devices.
- A visual jump can appear when the client render replaces the server render.
- Event replay and incremental hydration do not help that subtree, because there is nothing to hydrate.
Try these alternatives first, in roughly this order:
- Move the DOM work later. Use
afterNextRenderorafterRenderso the mutation happens after hydration, as in the first example above. This is the right fix for most direct DOM manipulation. - Fix invalid HTML. A
<div>inside a<p>, or a<table>without a<tbody>where the parser inserts one, causes mismatches. Correct the template and the problem goes away. - Use Angular APIs instead of the raw DOM. Prefer templates,
Renderer2, and bindings overinnerHTMLandappendChildon template nodes. - Render only in the browser. If a component has no useful server output, you can avoid server rendering for it through a platform check, or choose
RenderMode.Clientfor the whole route.
Reach for ngSkipHydration when the code is not yours to change, as with a third-party library, or when a rewrite is not worth the effort right now.
Choosing between skip hydration and client-only rendering
Skipping hydration still renders the component on the server. A different approach is to render nothing on the server for the component, and create it only in the browser. Compare them.
| Approach | Server HTML for the component | Browser work | Typical use |
|---|---|---|---|
| `ngSkipHydration` | Present, then discarded | Full re-render | The server output is useful for SEO or first paint, but the DOM is unsafe to reuse. |
| Browser-only guard with `isPlatformBrowser` or `afterNextRender` | Empty or placeholder | Renders once | The component needs `window` or the DOM and has no meaningful server output. |
| `RenderMode.Client` on the route | None for the whole page | Full page render | The entire route depends on browser state. |
If the server output is blank or meaningless, a placeholder with an @if on a browser flag is cheaper than skipping hydration, because the server does no extra work.
import { Component, PLATFORM_ID, inject, signal, afterNextRender } from '@angular/core';
@Component({
selector: 'app-map-slot',
template: `
@if (ready()) {
<app-legacy-map />
} @else {
<p>Loading map...</p>
}
`,
})
export class MapSlotComponent {
protected ready = signal(false);
constructor() {
afterNextRender(() => this.ready.set(true));
}
}The server renders the placeholder paragraph. After hydration, the signal flips and the map component is created in the browser as a normal new view, so there is no mismatch to resolve.
Diagnosing whether you need it
Follow this flow when a hydration error appears.
The error message names the component and gives a DOM path, which tells you which host element to mark if you reach the last branch. After you add the attribute, reload and confirm that the error is gone and that the rest of the page still hydrates.
Common mistakes
- Putting the attribute on a non-component element. Angular ignores it and reports an error in development. Move it to a component host.
- Using it as a first response to any error. Many mismatches are one-line template fixes. Skipping hides the real bug and keeps the cost.
- Skipping a large parent. Every descendant loses hydration. Mark the narrowest component instead.
- Expecting event replay to cover it. Events on a skipped subtree are handled once the browser has rendered the component, not replayed from before.
- Leaving it in place after the library is upgraded. Revisit each opt-out when you update the dependency. The new version might work with hydration, and removing the attribute recovers the performance.
Exercise
A component app-rich-editor wraps a library that calls innerHTML on its container during construction, which causes a hydration mismatch. The rest of the page is fine. Where do you apply ngSkipHydration, and what happens to the editor's server-rendered HTML?
Show answer
Apply it to the app-rich-editor host element, either in the parent template as <app-rich-editor ngSkipHydration /> or in the component's host metadata as host: { ngSkipHydration: 'true' }. Angular leaves the editor's server-rendered DOM unused, removes it, and renders the editor from scratch in the browser. The rest of the page stays hydrated. Do not put the attribute on the root component, because that would turn off hydration for the whole application.
Exercise
You add ngSkipHydration to a plain <div> inside a component template, and the mismatch is still there. Why, and what do you do?
Show answer
The attribute only works on the host element of a component. A plain <div> is not a component host, so Angular ignores the attribute. Move the problematic markup into its own component and put ngSkipHydration on that component's host. Better still, fix the cause, for example by moving the DOM change into afterNextRender or correcting invalid HTML.
Exercise
A component needs window and has no useful server output. Is ngSkipHydration the best choice? Explain.
Show answer
No. Skipping hydration still renders the component on the server and then discards that HTML, which wastes work. A cheaper option is to render a placeholder on the server and create the real content after afterNextRender flips a signal, or to render the whole route with RenderMode.Client if the entire page depends on browser state.