Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion packages/core/src/hydration/error_handling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,17 @@ export function validateMatchingNode(
tNode: TNode,
isViewContainerAnchor = false,
): void {
const hasStaticTextContentMismatch = hasTextContentMismatch(node, tNode);

if (
!node ||
(node as Node).nodeType !== nodeType ||
hasStaticTextContentMismatch ||
((node as Node).nodeType === Node.ELEMENT_NODE &&
(node as HTMLElement).tagName.toLowerCase() !== tagName?.toLowerCase())
) {
const expectedNode = shortRNodeDescription(nodeType, tagName, null);
const expectedTextContent = hasStaticTextContentMismatch ? tNode.value : null;
const expectedNode = shortRNodeDescription(nodeType, tagName, expectedTextContent);
let header = `During hydration Angular expected ${expectedNode} but `;

const hostComponentDef = getDeclarationComponentDef(lView);
Expand Down Expand Up @@ -120,6 +124,16 @@ export function validateMatchingNode(
}
}

function hasTextContentMismatch(node: RNode | null, tNode: TNode): boolean {
return (
node !== null &&
(node as Node).nodeType === Node.TEXT_NODE &&
tNode.type === TNodeType.Text &&
tNode.value.length > 0 &&
(node as Node).textContent !== tNode.value
);
}

/**
* Validates that a given node has sibling nodes
*/
Expand Down
35 changes: 35 additions & 0 deletions packages/platform-server/test/full_app_hydration_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6174,6 +6174,41 @@ describe('platform-server full application hydration integration', () => {
});
});

it('should detect static text content mismatch', async () => {
@Component({
selector: 'app',
template: `
<ul>
<li><span>Alice</span><button>Delete</button></li>
</ul>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
private isServer = isPlatformServer(inject(PLATFORM_ID));

ngAfterViewInit() {
if (this.isServer) {
const injectedItem = this.doc.createElement('li');
injectedItem.innerHTML = '<span>Sponsored</span><button>Visit ad</button>';
this.doc.querySelector('li')?.before(injectedItem);
}
}
}

const html = await ssr(SimpleComponent);

resetTViewsFor(SimpleComponent);

await expectAsync(
prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}),
).toBeRejectedWithError(
/During hydration Angular expected a text node \(with the "Alice" content\) but found a text node \(with the "Sponsored" content\)/,
);
});

it('should not crash when a node can not be found during hydration', async () => {
@Component({
selector: 'app',
Expand Down