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 and 22.3.0 (the current latest), in development and production builds.
Description
With hydration enabled, content projected through an <ng-content> slot is lost when all of these hold:
- A component template (
WrapperComponent) places an<ng-content />inside an element, for example<div><ng-content /></div>, in the content of another component (<app-container>). - The other component (
ContainerComponent) does not render its own<ng-content>on the server, for example because the slot sits inside an@ifthat isfalse. - The condition becomes
trueafter hydration.
The server render succeeds, hydration reports no error, and the server DOM is reused. But once the container opens, it shows an empty <div>: the projected text is missing. It stays missing after closing and opening the container again. Nothing is logged in the console.
Without provideClientHydration(), or with the condition already true on the server, the text is there.
Results in headless Chromium (Chrome for Testing 156). The development and production builds give the same results:
Template inside <app-container [open]="open()"> |
open on the server |
provideClientHydration() |
<app-container> after opening |
|---|---|---|---|
<div><ng-content /></div> |
false |
yes | <div></div> |
<div><ng-content /></div> |
false |
no | <div>projected text</div> |
<div><ng-content /></div> |
true |
yes | <div>projected text</div> |
Boundaries, with hydration and open set to false on the server. <app-box> is a component whose template is only <ng-content />.
Template inside <app-container [open]="open()"> |
<app-container> after opening |
|---|---|
<div><span><ng-content /></span></div> |
<div><span></span></div> |
<div><ng-container><ng-content /></ng-container></div> |
<div></div> |
<div><b>before</b><ng-content /></div> |
<div><b>before</b></div> |
<div><ng-content /></div>, with <b>projected element</b> projected into <app-wrapper> |
<div></div> |
<div><ng-content select="b" /><ng-content /></div>, with <b>b</b> text projected |
<div></div> |
<app-box><div><ng-content /></div></app-box> |
<app-box><div></div></app-box> |
<ng-content /> |
projected text (correct) |
<ng-container><ng-content /></ng-container> |
projected text (correct) |
@if (true) { <div><ng-content /></div> } |
<div>projected text</div> (correct) |
<div><app-box><ng-content /></app-box></div> |
<div><app-box>projected text</app-box></div> (correct) |
In every row, the page hydrates with no NG05xx error and reuses the server-rendered <button>, <app-wrapper> and <app-container>.
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 server
node dist/repro/server/server.mjs
# open http://localhost:4000/ and click "toggle"src/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()">
<div><ng-content /></div>
</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 }). To serve the build on localhost, angular.json has "allowedHosts": ["localhost"] under security.
Please provide the exception or error you saw
There is no exception. The prerendered / (production build) is:
<app-root ng-version="22.3.0" ngh="2" ng-server-context="ssg"><button id="toggle" jsaction="click:;">toggle</button><app-wrapper ngh="1"><app-container ngh="0"><!----></app-container></app-wrapper></app-root>with this __nghData__:
[{"t":{"0":"t0"},"c":{"0":[]}},{"d":[1]},{"d":[3]}]After hydration and one click on "toggle", the content of <app-container> is <div></div>. Without provideClientHydration(), it is <div>projected text</div>.
The console of the development build only has:
Angular is running in development mode.
Angular hydrated 3 component(s) and 9 node(s), 0 component(s) were skipped. 0 defer block(s) were configured to use incremental hydration. Learn more at https://v22.angular.dev/guide/hydration.
The production build logs nothing.
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 │
└───────────────────────────┴───────────────────┴───────────────────┘
The same app also loses the content on 21.2.26 and on 20.3.35 (with provideZoneChangeDetection({ eventCoalescing: true }) added on 20.x, as generated), in development and production builds.
Anything else?
Cause
On the server, <app-container> does not render its slot, so the <div> and the projected text never reach the document. serializeLView records them as disconnected: in the __nghData__ above, "d":[1] is the <div> in WrapperComponent and "d":[3] is the text in App.
On the client:
- The text node in
Appis created, because it is disconnected. It is not inserted anywhere yet: its parent is the<app-wrapper>host, and the content of a component is inserted by that component'sɵɵprojection. - In
WrapperComponent,ɵɵelementStartfor the<div>callscanHydrateNode, which returnsfalsefor a disconnected node, so a new<div>is created. ɵɵprojectionfor the<ng-content />inside that<div>skipsapplyProjection, because the view has hydration info.- When
openbecomestrue, the@ifview ofContainerComponentis created without hydration info. Itsɵɵprojectionmoves the<div>into<app-container>, and the<div>is still empty.
Step 3 is in packages/core/src/render3/instructions/projection.ts#L194-L204 (main at 7391654):
const hydrationInfo = lView[HYDRATION];
const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock();
const componentHostNode = lView[DECLARATION_COMPONENT_VIEW][T_HOST] as TElementNode;
const isEmpty = componentHostNode.projection![tProjectionNode.projection] === null;
if (isEmpty && fallbackIndex !== null) {
insertFallbackContent(lView, tView, fallbackIndex);
} else if (isNodeCreationMode && !isDetachedByI18n(tProjectionNode)) {
// re-distribution of projectable nodes is stored on a component's view level
applyProjection(tView, lView, tProjectionNode);
}Skipping applyProjection while hydrating is right when the slot's parent was hydrated, because the projected nodes are already in it. Here the parent was created on the client, so the projected nodes were created on the client too, and nothing inserts them.
The rows of the boundaries table that work match this reading:
- With
<ng-content />directly in<app-container>, or inside an<ng-container>, step 4 inserts the text, becauseapplyProjectionRecursivewalks into nested<ng-content>slots and into the children of<ng-container>. It does not walk into the children of an element. - With
<div><app-box><ng-content /></app-box></div>, the host of<app-box>is created on the client, so its view has no hydration info and its ownɵɵprojectioninserts the text. - With
@if (true) { <div><ng-content /></div> }, the@ifview is created without hydration info, so itsɵɵprojectionruns in creation mode.
Proposed fix
Treat the slot as being in creation mode when its parent was not hydrated. canHydrateNode (packages/core/src/hydration/utils.ts#L523-L532) is the check that the element, <ng-container>, text and template instructions already use, through their locateOrCreate… functions, to decide whether to create a node. Applied to the slot's parent, it tells whether that parent was created on the client.
--- a/packages/core/src/render3/instructions/projection.ts
+++ b/packages/core/src/render3/instructions/projection.ts
@@ -5,6 +5,7 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
+import {canHydrateNode} from '../../hydration/utils';
import {findMatchingDehydratedView} from '../../hydration/views';
import {isDetachedByI18n} from '../../i18n/utils';
import {newArray} from '../../util/array_utils';
@@ -192,7 +193,15 @@
setCurrentTNodeAsNotParent();
const hydrationInfo = lView[HYDRATION];
- const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock();
+ const parentTNode = tProjectionNode.parent;
+ // While hydrating, the projected nodes are already in place in the DOM, so they are not
+ // inserted again. The exception is a slot whose parent was created on the client: it was
+ // disconnected from the DOM on the server (for example, inside content that was not
+ // projected), so the projected nodes were created on the client as well and must be inserted.
+ const isNodeCreationMode =
+ !hydrationInfo ||
+ isInSkipHydrationBlock() ||
+ (parentTNode !== null && !canHydrateNode(lView, parentTNode));
const componentHostNode = lView[DECLARATION_COMPONENT_VIEW][T_HOST] as TElementNode;
const isEmpty = componentHostNode.projection![tProjectionNode.projection] === null;text.ts, element.ts, element_container.ts and template.ts in the same folder already import canHydrateNode from ../../hydration/utils.
I applied the same condition to the compiled @angular/core 22.3.0 of the reproduction (fesm2022/_debug_node-chunk.mjs, in ɵɵprojection) and ran every row above, in development and production builds:
- Every row that lost the content now shows it:
<div>projected text</div>,<div><span>projected text</span></div>,<div><b>before</b>projected text</div>,<div><b>projected element</b></div>,<div><b>b</b> text</div>,<app-box><div>projected text</div></app-box>. It hides on the second click and shows again on the third. - The rows that already worked give the same content as without the change, including
openset totrueon the server, where the server-rendered<div>is reused. - The server output does not change: the prerendered HTML and
__nghData__are identical with and without the change. The change only affects the client, sincewithDomHydrationdoes not enable the hydration runtime whenngServerModeis set, solView[HYDRATION]isnullon the server. - Hydration does not change: the server-rendered
<button>,<app-wrapper>and<app-container>are reused, the development build logs the sameAngular hydrated N component(s) and M node(s)counts as without the change, and there is no NG05xx error or any other console output.
It also does not interact with #72129. With and without the one-line fix proposed there, in development and production builds, the rows of the #72129 table give the results below. The fix in #72131 narrows that condition to content-projected nodes; every node that follows a slot in these rows is projected into <app-container>, so the condition matches the same nodes there.
Template inside <app-container [open]="open()"> |
open on the server |
Unpatched | #72129 fix | This fix | Both |
|---|---|---|---|---|---|
<ng-content />@if (true) { <p>after</p> } |
false |
NG0502 | projected text<p>after</p> |
NG0502 | projected text<p>after</p> |
<ng-content />@if (true) { <p>after</p> } |
true |
projected text<p>after</p> |
same | same | same |
<ng-content /> |
false |
projected text |
same | same | same |
<ng-content /><p>after</p> |
false |
NG0502 | projected text<p>after</p> |
NG0502 | projected text<p>after</p> |
<ng-content />after |
false |
NG0502 | projected textafter |
NG0502 | projected textafter |
<ng-content /><ng-container>after</ng-container> |
false |
NG0502 | projected textafter |
NG0502 | projected textafter |
<ng-content />@for (i of [1]; track i) { <p>{{ i }}</p> } |
false |
NG0502 | projected text<p>1</p> |
NG0502 | projected text<p>1</p> |
<div><ng-content />@if (true) { <p>after</p> }</div> |
false |
NG0502 | <div><p>after</p></div> |
NG0502 | <div>projected text<p>after</p></div> |
<p>before</p><ng-content /> |
false |
<p>before</p>projected text |
same | same | same |
<ng-content select="b" /><ng-content /> |
false |
projected text |
same | same | same |
@let x = 1;@if (true) { <p>{{ x }}</p> } (no <ng-content>) |
false |
NG0502 | <p>1</p> |
NG0502 | <p>1</p> |
<ng-content />@let x = 1; |
false |
projected text |
same | same | same |
The <div> row needs both fixes: the #72129 fix lets it render on the server, and this fix restores the projected text in the <div>.
A narrower alternative only checks the disconnected-node list: parentTNode !== null && isDisconnectedNode(hydrationInfo, parentTNode.index - HEADER_OFFSET). It gave the same results on every row above. canHydrateNode also covers a parent detached by i18n, which I did not test.
I have not run Angular's own test suite with the change.
Suggested regression test
In packages/platform-server/test/full_app_hydration_spec.ts, in describe('partial projection'), next to "should support cases when some element nodes are not projected (@if)" (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 project content into an element that was not projected on the server', 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">
<div><ng-content /></div>
</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');
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 > div').textContent).toBe('projected text');
});Without the fix, I expect the last expectation to fail with an empty <div>, as in the reproduction.
Related
- NG0502 during hydration serialization when a node follows
<ng-content>in content that is not projected #72129: same family (nodes in content that is not projected), but a different mechanism. That bug fails on the server, inserializeLView, when a node follows<ng-content>. This one happens on the client, inɵɵprojection, and needs no sibling. The two fixes are independent. fix(core): avoid NG0502 for nodes after<ng-content>or@letin content that is not projected #72131 is the pull request for NG0502 during hydration serialization when a node follows<ng-content>in content that is not projected #72129. - Possibly related: hydration problems with ng-content #50175 reported the same symptom in 2023 ("the ng-content is filled with nothing", with Angular Material). According to the analysis in that issue, its cause was a view container projected into a component that skips hydration, and it was fixed in 16.0.1.
Activity
fix(core): restore projection into recreated hydration nodes
test(core): cover nested projection across hydration and toggles