Repository navigation
Description
Which @angular/* package(s) are the source of the bug?
core
Is this a regression?
No
It reproduces on 20.3.35, 21.2.26, 22.2.1, 22.3.0-rc.0 (the current next tag) and 22.3.0 (the current latest).
Description
With hydration enabled, server rendering fails with NG0502: During serialization, Angular was unable to find an element in the DOM when all of these hold:
- A component template (
WrapperComponent) places<ng-content />inside the content of another component (<app-container>). - In that content, a node follows the
<ng-content />as a sibling: a control-flow block, an element, a text node, an<ng-container>, or a@for. - The other component (
ContainerComponent) does not render its own<ng-content>on the server, for example because the slot sits inside an@ifthat is false.
Content that is not projected is a supported case. Hydration marks such nodes as disconnected (appendDisconnectedNodeIndex), and the existing test "should support cases when some element nodes are not projected (@if)" covers it. The failure only happens when a sibling follows the <ng-content />.
The same failure happens with no <ng-content> at all when a @let declaration is followed by a sibling in content that is not projected. @let and <ng-content> share the same branch of serializeLView.
Boundaries (ng build, which prerenders /):
Template inside <app-container [open]="open()"> |
open on the server |
Result |
|---|---|---|
<ng-content />@if (true) { <p>after</p> } |
false |
NG0502 |
<ng-content />@if (true) { <p>after</p> } |
true |
OK |
<ng-content /> |
false |
OK |
<ng-content /><p>after</p> |
false |
NG0502 |
<ng-content />after |
false |
NG0502 |
<ng-content /><ng-container>after</ng-container> |
false |
NG0502 |
<ng-content />@for (i of [1]; track i) { <p>{{ i }}</p> } |
false |
NG0502 |
<div><ng-content />@if (true) { <p>after</p> }</div> |
false |
NG0502 |
<p>before</p><ng-content /> |
false |
OK |
<ng-content select="b" /><ng-content /> |
false |
OK |
@let x = 1;@if (true) { <p>{{ x }}</p> } (no <ng-content>) |
false |
NG0502 |
<ng-content />@let x = 1; |
false |
OK |
The bug does not depend on what is projected into <app-wrapper>: it also fails when nothing is projected.
With RenderMode.Server instead of prerendering (and localhost in security.allowedHosts), the request answers HTTP 200 with the body Internal server error. and nothing is logged, because the error happens while the response streams.
Please provide a link to a minimal reproduction of the bug
Inline reproduction, no third-party libraries.
npx @angular/cli@22.3.0 new repro --ssr --defaults --skip-git
cd repro
rm src/app/app.html src/app/app.css src/app/app.spec.ts
# add the files below
npx ng build # the default app.routes.server.ts prerenders '**', so the build renders '/' on the serversrc/app/container.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-container',
template: `
@if (open()) {
<ng-content />
}
`,
})
export class ContainerComponent {
readonly open = input(false);
}src/app/wrapper.ts
import { Component, input } from '@angular/core';
import { ContainerComponent } from './container';
@Component({
selector: 'app-wrapper',
imports: [ContainerComponent],
template: `
<app-container [open]="open()">
<ng-content />
@if (true) {
<p>after</p>
}
</app-container>
`,
})
export class WrapperComponent {
readonly open = input(false);
}src/app/app.ts
import { Component, signal } from '@angular/core';
import { WrapperComponent } from './wrapper';
@Component({
selector: 'app-root',
imports: [WrapperComponent],
template: `
<button id="toggle" (click)="open.set(!open())">toggle</button>
<app-wrapper [open]="open()">projected text</app-wrapper>
`,
})
export class App {
protected readonly open = signal(false);
}src/app/app.config.ts (the generated providers, unchanged)
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideClientHydration } from '@angular/platform-browser';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes), provideClientHydration()],
};src/app/app.config.server.ts and src/app/app.routes.server.ts are the generated ones (provideServerRendering(withRoutes(serverRoutes)), { path: '**', renderMode: RenderMode.Prerender }).
Please provide the exception or error you saw
npx ng build --configuration development, with NODE_OPTIONS=--stack-trace-limit=100, on 22.3.0 (prerender paths shortened to <prerender>):
✘ [ERROR] An error occurred while prerendering route '/'.
Error: NG0502: During serialization, Angular was unable to find an element in the DOM:
…
#node(projection)
<!-- container --> <-- AT THIS LOCATION
…
To fix this problem:
* check corresponding component for hydration-related issues
* check to see if your template has valid HTML structure
* check if there are any third-party scripts that manipulate the DOM. More info: https://v22.angular.dev/guide/hydration#third-party-scripts-with-dom-manipulation
* or skip hydration by adding the `ngSkipHydration` attribute to its host node in a template
Find more at https://v22.angular.dev/errors/NG0502
at nodeNotFoundError (<prerender>/node_modules/@angular/core/fesm2022/_debug_node-chunk.mjs:6805:9)
at calcPathForNode (<prerender>/node_modules/@angular/core/fesm2022/_debug_node-chunk.mjs:7470:13)
at appendSerializedNodePath (<prerender>/node_modules/@angular/core/fesm2022/core.mjs:2678:33)
at serializeLView (<prerender>/node_modules/@angular/core/fesm2022/core.mjs:2765:11)
at annotateHostElementForHydration (<prerender>/node_modules/@angular/core/fesm2022/core.mjs:2804:17)
at serializeLView (<prerender>/node_modules/@angular/core/fesm2022/core.mjs:2753:9)
at annotateHostElementForHydration (<prerender>/node_modules/@angular/core/fesm2022/core.mjs:2804:17)
at annotateComponentLViewForHydration (<prerender>/node_modules/@angular/core/fesm2022/core.mjs:2496:12)
at annotateForHydration (<prerender>/node_modules/@angular/core/fesm2022/core.mjs:2543:9)
at prepareForHydration (<prerender>/node_modules/@angular/platform-server/fesm2022/platform-server.mjs:65:30)
at renderInternal (<prerender>/node_modules/@angular/platform-server/fesm2022/platform-server.mjs:105:3)
at Timeout.<anonymous> (<prerender>/node_modules/@angular/ssr/fesm2022/ssr.mjs:406:11)
at listOnTimeout (node:internal/timers:685:17)
at process.processTimers (node:internal/timers:618:7)
The production build (npx ng build) prints the same message. On 22.2.1 the stack is the same, with serializeLView at core.mjs:2752.
Please provide the environment you discovered this bug in (run ng version)
Angular CLI : 22.3.0
Angular : 22.3.0
Node.js : 24.22.3
Package Manager : npm 11.19.1
Operating System : linux x64
┌───────────────────────────┬───────────────────┬───────────────────┐
│ Package │ Installed Version │ Requested Version │
├───────────────────────────┼───────────────────┼───────────────────┤
│ @angular/build │ 22.3.0 │ 22.3.0 │
│ @angular/cli │ 22.3.0 │ 22.3.0 │
│ @angular/common │ 22.3.0 │ 22.3.0 │
│ @angular/compiler │ 22.3.0 │ 22.3.0 │
│ @angular/compiler-cli │ 22.3.0 │ 22.3.0 │
│ @angular/core │ 22.3.0 │ 22.3.0 │
│ @angular/forms │ 22.3.0 │ 22.3.0 │
│ @angular/platform-browser │ 22.3.0 │ 22.3.0 │
│ @angular/platform-server │ 22.3.0 │ 22.3.0 │
│ @angular/router │ 22.3.0 │ 22.3.0 │
│ @angular/ssr │ 22.3.0 │ 22.3.0 │
│ rxjs │ 7.8.2 │ ~7.8.0 │
│ typescript │ 6.0.3 │ ~6.0.2 │
│ vitest │ 5.1.1 │ ^5.0.0 │
└───────────────────────────┴───────────────────┴───────────────────┘
It also fails with the same packages at 22.2.1 and 22.3.0-rc.0, and with 21.2.26 and 20.3.35 (with provideZonelessChangeDetection() added on 20.x).
Anything else?
Cause
In serializeLView, the branch for <ng-content> slots and @let declarations stores a full path for the node that follows them, because that node cannot be located from a sibling anchor. It does not check whether that node is disconnected:
packages/core/src/hydration/annotate.ts#L707-L722 (main at 7391654):
} else if (tNode.type & (TNodeType.Projection | TNodeType.LetDeclaration)) {
// ...
let nextTNode = tNode.next;
// Skip over all `<ng-content>` slots and `@let` declarations in a row.
while (
nextTNode !== null &&
nextTNode.type & (TNodeType.Projection | TNodeType.LetDeclaration)
) {
nextTNode = nextTNode.next;
}
if (nextTNode && !isInSkipHydrationBlock(nextTNode)) {
// Handle a tNode after the `<ng-content>` slot.
appendSerializedNodePath(ngh, nextTNode, lView, i18nChildren);
}When the content is not projected, the next node (here the @if anchor comment) never reaches the document. calcPathForNode cannot find it from its parent or from <body>, and it throws nodeNotFoundError.
The <ng-content> / @let slot itself never counts as disconnected, because isDisconnectedNode excludes Projection and LetDeclaration nodes, so it always reaches this branch. The sibling's own iteration does record it as disconnected at line 613, but this branch computes a path for it anyway. The projection-head branch at lines 632-640 already guards the same situation with isDisconnectedNode.
Proposed fix
- if (nextTNode && !isInSkipHydrationBlock(nextTNode)) {
+ if (nextTNode && !isInSkipHydrationBlock(nextTNode) && !isDisconnectedNode(nextTNode, lView)) {I applied this change to the compiled @angular/core (fesm2022/core.mjs) of the reproduction on 22.2.1, 22.3.0-rc.0 and 22.3.0:
- Every row of the boundaries table builds and prerenders.
- The disconnected sibling is still serialized as disconnected by its own iteration. For the reproduction,
__nghData__is[{"t":{"0":"t0"},"c":{"0":[]}},{"t":{"2":"t1"},"d":[2]},{"d":[3]}]. - In Chromium (headless, dev and prod builds), the page hydrates. The dev build logs
Angular hydrated 3 component(s) and 9 node(s), 0 component(s) were skipped, with no NG05xx errors in the console. The server-rendered<button>,<app-wrapper>and<app-container>elements are reused. - After hydration, toggling
openrendersprojected text<p>after</p>inside<app-container>. It hides on the second click and renders again on the third.
An equivalent alternative is to mirror the projection-head branch (isDisconnectedNode → appendDisconnectedNodeIndex, else appendSerializedNodePath). It produced the same d indices and the same browser result. Unlike the one-line guard, it would also record the sibling as disconnected when it is not under a component host, which the line 613 check does not cover (I did not test that case).
Suggested regression test
In packages/platform-server/test/full_app_hydration_spec.ts, next to "should support cases when some element nodes are not projected (@if)" in describe('partial projection') (currently line 5393). It uses only helpers and symbols the spec already imports (Input, signal). I have not run it in the Angular repository.
it('should support a node after <ng-content> when the content is not projected (@if)', async () => {
@Component({
selector: 'app-container',
template: `
@if (open) {
<ng-content />
}
`,
})
class ContainerComponent {
@Input() open = false;
}
@Component({
selector: 'app-wrapper',
imports: [ContainerComponent],
template: `
<app-container [open]="open">
<ng-content />
@if (true) {
<p>after</p>
}
</app-container>
`,
})
class WrapperComponent {
@Input() open = false;
}
@Component({
selector: 'app',
imports: [WrapperComponent],
template: `<app-wrapper [open]="open()">projected text</app-wrapper>`,
})
class SimpleComponent {
open = signal(false);
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).not.toContain('projected text');
expect(ssrContents).not.toContain('<p>after</p>');
resetTViewsFor(SimpleComponent, WrapperComponent, ContainerComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
// The content that was not projected on the server renders once the slot opens.
compRef.instance.open.set(true);
appRef.tick();
expect(clientRootNode.querySelector('app-container').textContent).toContain('projected text');
expect(clientRootNode.querySelector('app-container > p').textContent).toBe('after');
});
it('should support a node after @let when the content is not projected', async () => {
@Component({
selector: 'app-container',
template: `
@if (false) {
<ng-content />
}
`,
})
class ContainerComponent {}
@Component({
selector: 'app',
imports: [ContainerComponent],
template: `
<app-container>
@let label = 'after';
@if (true) {
<p>{{ label }}</p>
}
</app-container>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ContainerComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});Without the fix, both tests fail inside ssr(...) with NG0502. The @let is read inside the @if so that the compiler keeps a @let node: a @let read only in its own view is compiled to a local constant, and then nothing fails.
Related, but separate
While testing the <div> row of the table, I found a second problem that this fix does not cause and does not address. With <div><ng-content /></div> (no sibling, so the server render already succeeds without the fix) inside content that is not projected, the hydrated page shows an empty <div> once open becomes true: the projected text is missing. Without provideClientHydration(), the text is there. ɵɵprojection skips applyProjection while hydrating, but here the parent <div> was disconnected on the server and is created fresh on the client. I can file that separately.
Activity