angular / components

Component infrastructure and Material Design components for Angular

Home Page:https://material.angular.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

bug(CdkPortal): Change detection loop when component portal uses NgModel

meriturva opened this issue · comments

Is this a regression?

  • Yes, this behavior used to work in the previous version

The previous version in which this bug was not present was

No response

Description

Adding a ngModel to a ComponentPortal makes change detection loop!

Reproduction

Just clone repo:

https://github.com/meriturva/cdkPortal-NgModel-CD-Loop

Please comment on that line to make it work again:
https://github.com/meriturva/cdkPortal-NgModel-CD-Loop/blob/main/src/app/text-editor/text-editor.component.html#L4

Expected Behavior

Works correctly!

Actual Behavior

Loop during change detection.

Environment

Angular CLI: 17.3.7
Node: 20.12.2
Package Manager: npm 10.5.0
OS: win32 x64

Angular: 17.3.7
... animations, cdk, cli, common, compiler, compiler-cli, core
... forms, platform-browser, platform-browser-dynamic, router

Package Version

@angular-devkit/architect 0.1703.7
@angular-devkit/build-angular 17.3.7
@angular-devkit/core 17.3.7
@angular-devkit/schematics 17.3.7
@schematics/angular 17.3.7
rxjs 7.8.1
typescript 5.4.5
zone.js 0.14.5

This line in your code is the problem: https://github.com/meriturva/cdkPortal-NgModel-CD-Loop/blob/main/src/app/viewer/viewer.component.html#L3

It means that every time change detection runs, it'll return a brand-new portal which will then re-render since Angular will compare them by reference. You should consider caching the portals so that they're only created once.

Thanks @crisbeto for loop with track options it doesn't prevent re-run cd. Thats clear. But the introduction of Signal Components and local change detection could prevent it in the future?

Signals might prevent it from running continuously, but having getComponentPortal return a new portal every time is still inefficient since the portal itself isn't changing.

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.