Skip to content

Hydration: projected content is missing when <ng-content> sits inside an element that was not projected on the server #72132

Open

Description

@floxcristian

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:

  1. 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>).
  2. The other component (ContainerComponent) does not render its own <ng-content> on the server, for example because the slot sits inside an @if that is false.
  3. The condition becomes true after 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:

  1. The text node in App is 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.
  2. In WrapperComponent, ɵɵelementStart for the <div> calls canHydrateNode, which returns false for a disconnected node, so a new <div> is created.
  3. ɵɵprojection for the <ng-content /> inside that <div> skips applyProjection, because the view has hydration info.
  4. When open becomes true, the @if view of ContainerComponent is created without hydration info. Its ɵɵprojection moves 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, because applyProjectionRecursive walks 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 ɵɵprojection inserts the text.
  • With @if (true) { <div><ng-content /></div> }, the @if view is created without hydration info, so its ɵɵprojection runs 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 open set to true on 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, since withDomHydration does not enable the hydration runtime when ngServerMode is set, so lView[HYDRATION] is null on the server.
  • Hydration does not change: the server-rendered <button>, <app-wrapper> and <app-container> are reused, the development build logs the same Angular 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: core

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions