Title: NG0502 during hydration serialization when a node follows `
Open Graph Title: NG0502 during hydration serialization when a node follows `
X Title: NG0502 during hydration serialization when a node follows `
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, serve...
Open Graph 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). D...
X 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). D...
Opengraph URL: https://github.com/angular/angular/issues/72129
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"NG0502 during hydration serialization when a node follows `\u003cng-content>` in content that is not projected","articleBody":"### Which @angular/* package(s) are the source of the bug?\n\ncore\n\n### Is this a regression?\n\nNo\n\nIt 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`).\n\n### Description\n\nWith hydration enabled, server rendering fails with `NG0502: During serialization, Angular was unable to find an element in the DOM` when all of these hold:\n\n1. A component template (`WrapperComponent`) places `\u003cng-content />` inside the content of another component (`\u003capp-container>`).\n2. In that content, a node follows the `\u003cng-content />` as a sibling: a control-flow block, an element, a text node, an `\u003cng-container>`, or a `@for`.\n3. The other component (`ContainerComponent`) does not render its own `\u003cng-content>` on the server, for example because the slot sits inside an `@if` that is false.\n\nContent 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 `\u003cng-content />`.\n\nThe same failure happens with no `\u003cng-content>` at all when a `@let` declaration is followed by a sibling in content that is not projected. `@let` and `\u003cng-content>` share the same branch of `serializeLView`.\n\nBoundaries (`ng build`, which prerenders `/`):\n\n| Template inside `\u003capp-container [open]=\"open()\">` | `open` on the server | Result |\n| --- | --- | --- |\n| `\u003cng-content />@if (true) { \u003cp>after\u003c/p> }` | `false` | NG0502 |\n| `\u003cng-content />@if (true) { \u003cp>after\u003c/p> }` | `true` | OK |\n| `\u003cng-content />` | `false` | OK |\n| `\u003cng-content />\u003cp>after\u003c/p>` | `false` | NG0502 |\n| `\u003cng-content />after` | `false` | NG0502 |\n| `\u003cng-content />\u003cng-container>after\u003c/ng-container>` | `false` | NG0502 |\n| `\u003cng-content />@for (i of [1]; track i) { \u003cp>{{ i }}\u003c/p> }` | `false` | NG0502 |\n| `\u003cdiv>\u003cng-content />@if (true) { \u003cp>after\u003c/p> }\u003c/div>` | `false` | NG0502 |\n| `\u003cp>before\u003c/p>\u003cng-content />` | `false` | OK |\n| `\u003cng-content select=\"b\" />\u003cng-content />` | `false` | OK |\n| `@let x = 1;@if (true) { \u003cp>{{ x }}\u003c/p> }` (no `\u003cng-content>`) | `false` | NG0502 |\n| `\u003cng-content />@let x = 1;` | `false` | OK |\n\nThe bug does not depend on what is projected into `\u003capp-wrapper>`: it also fails when nothing is projected.\n\nWith `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.\n\n### Please provide a link to a minimal reproduction of the bug\n\nInline reproduction, no third-party libraries.\n\n```sh\nnpx @angular/cli@22.3.0 new repro --ssr --defaults --skip-git\ncd repro\nrm src/app/app.html src/app/app.css src/app/app.spec.ts\n# add the files below\nnpx ng build # the default app.routes.server.ts prerenders '**', so the build renders '/' on the server\n```\n\n`src/app/container.ts`\n\n```ts\nimport { Component, input } from '@angular/core';\n\n@Component({\n selector: 'app-container',\n template: `\n @if (open()) {\n \u003cng-content />\n }\n `,\n})\nexport class ContainerComponent {\n readonly open = input(false);\n}\n```\n\n`src/app/wrapper.ts`\n\n```ts\nimport { Component, input } from '@angular/core';\nimport { ContainerComponent } from './container';\n\n@Component({\n selector: 'app-wrapper',\n imports: [ContainerComponent],\n template: `\n \u003capp-container [open]=\"open()\">\n \u003cng-content />\n @if (true) {\n \u003cp>after\u003c/p>\n }\n \u003c/app-container>\n `,\n})\nexport class WrapperComponent {\n readonly open = input(false);\n}\n```\n\n`src/app/app.ts`\n\n```ts\nimport { Component, signal } from '@angular/core';\nimport { WrapperComponent } from './wrapper';\n\n@Component({\n selector: 'app-root',\n imports: [WrapperComponent],\n template: `\n \u003cbutton id=\"toggle\" (click)=\"open.set(!open())\">toggle\u003c/button>\n \u003capp-wrapper [open]=\"open()\">projected text\u003c/app-wrapper>\n `,\n})\nexport class App {\n protected readonly open = signal(false);\n}\n```\n\n`src/app/app.config.ts` (the generated providers, unchanged)\n\n```ts\nimport { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';\nimport { provideRouter } from '@angular/router';\nimport { provideClientHydration } from '@angular/platform-browser';\nimport { routes } from './app.routes';\n\nexport const appConfig: ApplicationConfig = {\n providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes), provideClientHydration()],\n};\n```\n\n`src/app/app.config.server.ts` and `src/app/app.routes.server.ts` are the generated ones (`provideServerRendering(withRoutes(serverRoutes))`, `{ path: '**', renderMode: RenderMode.Prerender }`).\n\n### Please provide the exception or error you saw\n\n`npx ng build --configuration development`, with `NODE_OPTIONS=--stack-trace-limit=100`, on 22.3.0 (prerender paths shortened to `\u003cprerender>`):\n\n```\n✘ [ERROR] An error occurred while prerendering route '/'.\n\nError: NG0502: During serialization, Angular was unable to find an element in the DOM:\n\n …\n #node(projection)\n \u003c!-- container --> \u003c-- AT THIS LOCATION\n …\n\n\nTo fix this problem:\n * check corresponding component for hydration-related issues\n * check to see if your template has valid HTML structure\n * 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\n * or skip hydration by adding the `ngSkipHydration` attribute to its host node in a template\n\n Find more at https://v22.angular.dev/errors/NG0502\n at nodeNotFoundError (\u003cprerender>/node_modules/@angular/core/fesm2022/_debug_node-chunk.mjs:6805:9)\n at calcPathForNode (\u003cprerender>/node_modules/@angular/core/fesm2022/_debug_node-chunk.mjs:7470:13)\n at appendSerializedNodePath (\u003cprerender>/node_modules/@angular/core/fesm2022/core.mjs:2678:33)\n at serializeLView (\u003cprerender>/node_modules/@angular/core/fesm2022/core.mjs:2765:11)\n at annotateHostElementForHydration (\u003cprerender>/node_modules/@angular/core/fesm2022/core.mjs:2804:17)\n at serializeLView (\u003cprerender>/node_modules/@angular/core/fesm2022/core.mjs:2753:9)\n at annotateHostElementForHydration (\u003cprerender>/node_modules/@angular/core/fesm2022/core.mjs:2804:17)\n at annotateComponentLViewForHydration (\u003cprerender>/node_modules/@angular/core/fesm2022/core.mjs:2496:12)\n at annotateForHydration (\u003cprerender>/node_modules/@angular/core/fesm2022/core.mjs:2543:9)\n at prepareForHydration (\u003cprerender>/node_modules/@angular/platform-server/fesm2022/platform-server.mjs:65:30)\n at renderInternal (\u003cprerender>/node_modules/@angular/platform-server/fesm2022/platform-server.mjs:105:3)\n at Timeout.\u003canonymous> (\u003cprerender>/node_modules/@angular/ssr/fesm2022/ssr.mjs:406:11)\n at listOnTimeout (node:internal/timers:685:17)\n at process.processTimers (node:internal/timers:618:7)\n```\n\nThe production build (`npx ng build`) prints the same message. On 22.2.1 the stack is the same, with `serializeLView` at `core.mjs:2752`.\n\n### Please provide the environment you discovered this bug in (run `ng version`)\n\n```\nAngular CLI : 22.3.0\nAngular : 22.3.0\nNode.js : 24.22.3\nPackage Manager : npm 11.19.1\nOperating System : linux x64\n\n┌───────────────────────────┬───────────────────┬───────────────────┐\n│ Package │ Installed Version │ Requested Version │\n├───────────────────────────┼───────────────────┼───────────────────┤\n│ @angular/build │ 22.3.0 │ 22.3.0 │\n│ @angular/cli │ 22.3.0 │ 22.3.0 │\n│ @angular/common │ 22.3.0 │ 22.3.0 │\n│ @angular/compiler │ 22.3.0 │ 22.3.0 │\n│ @angular/compiler-cli │ 22.3.0 │ 22.3.0 │\n│ @angular/core │ 22.3.0 │ 22.3.0 │\n│ @angular/forms │ 22.3.0 │ 22.3.0 │\n│ @angular/platform-browser │ 22.3.0 │ 22.3.0 │\n│ @angular/platform-server │ 22.3.0 │ 22.3.0 │\n│ @angular/router │ 22.3.0 │ 22.3.0 │\n│ @angular/ssr │ 22.3.0 │ 22.3.0 │\n│ rxjs │ 7.8.2 │ ~7.8.0 │\n│ typescript │ 6.0.3 │ ~6.0.2 │\n│ vitest │ 5.1.1 │ ^5.0.0 │\n└───────────────────────────┴───────────────────┴───────────────────┘\n```\n\nIt 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).\n\n### Anything else?\n\n#### Cause\n\nIn `serializeLView`, the branch for `\u003cng-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:\n\n[`packages/core/src/hydration/annotate.ts#L707-L722`](https://github.com/angular/angular/blob/73916540c1688c0463617ef1469bf63adb0a628f/packages/core/src/hydration/annotate.ts#L707-L722) (`main` at `7391654`):\n\n```ts\n } else if (tNode.type & (TNodeType.Projection | TNodeType.LetDeclaration)) {\n // ...\n let nextTNode = tNode.next;\n // Skip over all `\u003cng-content>` slots and `@let` declarations in a row.\n while (\n nextTNode !== null &&\n nextTNode.type & (TNodeType.Projection | TNodeType.LetDeclaration)\n ) {\n nextTNode = nextTNode.next;\n }\n if (nextTNode && !isInSkipHydrationBlock(nextTNode)) {\n // Handle a tNode after the `\u003cng-content>` slot.\n appendSerializedNodePath(ngh, nextTNode, lView, i18nChildren);\n }\n```\n\nWhen 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 `\u003cbody>`, and it throws `nodeNotFoundError`.\n\nThe `\u003cng-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](https://github.com/angular/angular/blob/73916540c1688c0463617ef1469bf63adb0a628f/packages/core/src/hydration/annotate.ts#L613), but this branch computes a path for it anyway. The projection-head branch at [lines 632-640](https://github.com/angular/angular/blob/73916540c1688c0463617ef1469bf63adb0a628f/packages/core/src/hydration/annotate.ts#L632-L640) already guards the same situation with `isDisconnectedNode`.\n\n#### Proposed fix\n\n```diff\n- if (nextTNode && !isInSkipHydrationBlock(nextTNode)) {\n+ if (nextTNode && !isInSkipHydrationBlock(nextTNode) && !isDisconnectedNode(nextTNode, lView)) {\n```\n\nI 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:\n\n- Every row of the boundaries table builds and prerenders.\n- 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]}]`.\n- 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 `\u003cbutton>`, `\u003capp-wrapper>` and `\u003capp-container>` elements are reused.\n- After hydration, toggling `open` renders `projected text\u003cp>after\u003c/p>` inside `\u003capp-container>`. It hides on the second click and renders again on the third.\n\nAn 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).\n\n#### Suggested regression test\n\nIn `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](https://github.com/angular/angular/blob/73916540c1688c0463617ef1469bf63adb0a628f/packages/platform-server/test/full_app_hydration_spec.ts#L5393)). It uses only helpers and symbols the spec already imports (`Input`, `signal`). I have not run it in the Angular repository.\n\n```ts\nit('should support a node after \u003cng-content> when the content is not projected (@if)', async () => {\n @Component({\n selector: 'app-container',\n template: `\n @if (open) {\n \u003cng-content />\n }\n `,\n })\n class ContainerComponent {\n @Input() open = false;\n }\n\n @Component({\n selector: 'app-wrapper',\n imports: [ContainerComponent],\n template: `\n \u003capp-container [open]=\"open\">\n \u003cng-content />\n @if (true) {\n \u003cp>after\u003c/p>\n }\n \u003c/app-container>\n `,\n })\n class WrapperComponent {\n @Input() open = false;\n }\n\n @Component({\n selector: 'app',\n imports: [WrapperComponent],\n template: `\u003capp-wrapper [open]=\"open()\">projected text\u003c/app-wrapper>`,\n })\n class SimpleComponent {\n open = signal(false);\n }\n\n const html = await ssr(SimpleComponent);\n const ssrContents = getAppContents(html);\n\n expect(ssrContents).toContain('\u003capp ngh');\n expect(ssrContents).not.toContain('projected text');\n expect(ssrContents).not.toContain('\u003cp>after\u003c/p>');\n\n resetTViewsFor(SimpleComponent, WrapperComponent, ContainerComponent);\n\n const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);\n const compRef = getComponentRef\u003cSimpleComponent>(appRef);\n appRef.tick();\n\n const clientRootNode = compRef.location.nativeElement;\n verifyAllNodesClaimedForHydration(clientRootNode);\n verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);\n\n // The content that was not projected on the server renders once the slot opens.\n compRef.instance.open.set(true);\n appRef.tick();\n\n expect(clientRootNode.querySelector('app-container').textContent).toContain('projected text');\n expect(clientRootNode.querySelector('app-container > p').textContent).toBe('after');\n});\n\nit('should support a node after @let when the content is not projected', async () => {\n @Component({\n selector: 'app-container',\n template: `\n @if (false) {\n \u003cng-content />\n }\n `,\n })\n class ContainerComponent {}\n\n @Component({\n selector: 'app',\n imports: [ContainerComponent],\n template: `\n \u003capp-container>\n @let label = 'after';\n @if (true) {\n \u003cp>{{ label }}\u003c/p>\n }\n \u003c/app-container>\n `,\n })\n class SimpleComponent {}\n\n const html = await ssr(SimpleComponent);\n const ssrContents = getAppContents(html);\n\n expect(ssrContents).toContain('\u003capp ngh');\n\n resetTViewsFor(SimpleComponent, ContainerComponent);\n\n const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);\n const compRef = getComponentRef\u003cSimpleComponent>(appRef);\n appRef.tick();\n\n const clientRootNode = compRef.location.nativeElement;\n verifyAllNodesClaimedForHydration(clientRootNode);\n verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);\n});\n```\n\nWithout 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.\n\n#### Related, but separate\n\nWhile testing the `\u003cdiv>` row of the table, I found a second problem that this fix does not cause and does not address. With `\u003cdiv>\u003cng-content />\u003c/div>` (no sibling, so the server render already succeeds without the fix) inside content that is not projected, the hydrated page shows an empty `\u003cdiv>` once `open` becomes `true`: the projected text is missing. Without `provideClientHydration()`, the text is there. `ɵɵprojection` skips `applyProjection` while hydrating, but here the parent `\u003cdiv>` was disconnected on the server and is created fresh on the client. I can file that separately.\n","author":{"url":"https://github.com/floxcristian","@type":"Person","name":"floxcristian"},"datePublished":"2026-11-19T18:46:15Z","url":"https://github.com/angular/angular/issues/72129"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:611cdb7a-1894-e982-cffa-de24008131bc |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | EE30:3DCD28:F9C03F:14C119D:6B01DB8D |
| html-safe-nonce | c25d509297e713bc61d258249650f5e79ce089a1ddb4ea1578736dd57fcbcac2 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFRTMwOjNEQ0QyODpGOUMwM0Y6MTRDMTE5RDo2QjAxREI4RCIsInZpc2l0b3JfaWQiOiI3ODcwMTk5NjI5NDg3Mzk3NzczIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | a608ddfc826db5588a3d75682c5060ceaf51bcfd382867af2ba4281792bfc305 |
| hovercard-subject-tag | issue:6496650756 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/angular/angular/72129/issue_layout |
| twitter:image | https://opengraph.githubassets.com/2a0f7393453633e69bfbfc56cdaa489aa2c24282c900d0d6dcc22a66615665e5/angular/angular/issues/72129 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/2a0f7393453633e69bfbfc56cdaa489aa2c24282c900d0d6dcc22a66615665e5/angular/angular/issues/72129 |
| og:image:alt | 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). D... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | floxcristian |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| go-import | github.com/angular/angular git https://github.com/angular/angular.git |
| octolytics-dimension-user_id | 139426 |
| octolytics-dimension-user_login | angular |
| octolytics-dimension-repository_id | 24195339 |
| octolytics-dimension-repository_nwo | angular/angular |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 24195339 |
| octolytics-dimension-repository_network_root_nwo | angular/angular |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width