Skip to content

ComponentRef<T> onDestroyed() callback does not get called #39365

@ghost

Description

🐞 bug report

Affected Package

The issue is caused by package @angular/core

Is this a regression?

Yes, the previous version in which this bug was not present was: Pre-Ivy or if you disable Ivy

Description

Problem: ComponentRef.onDestroyed callback does not get called

A component gets dynamically created via ComponentFactoryResolver. It is then inserted into the view.

@ViewChild("anchor", { read: ViewContainerRef })
anchor: ViewContainerRef;
this.compRef = this.cfr
    .resolveComponentFactory(DynamicComponent)
    .create(this.injector);

this.compRef.onDestroy(() =>
    console.log("DynamicComponent onDestroyed callback")
);

this.anchor.insert(this.compRef.hostView);

As you can see, the onDestroyed callback is attached. If the component gets destroyed by its ComponentRef, the callback gets called correctly like so:

this.compRef.destroy();

if the component gets destroyed by clearing the anchor, the callback does not get called:

this.anchor.clear();

As far as I can tell, the onDestroyed callback ONLY gets called when the component gets destroyed by its ComponentRef. Whenever the component gets destroyed by clearing parent views or navigating away or data binding, the callback does not get called.

It works in NG 8.2.14 and it works if you set enableIvy: false in tsconfig.json.

🔬 Minimal Reproduction

https://stackblitz.com/edit/angular-ivy-ev4v2y

🌍 Your Environment

Angular Version:


Angular CLI: 10.1.6
Node: 12.18.1
OS: win32 x64

Angular: 10.1.5
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-webworker, router
Ivy Workspace: No

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1001.6
@angular-devkit/build-angular   0.1001.6
@angular-devkit/core            10.1.6
@angular-devkit/schematics      10.1.6
@angular/cdk                    10.2.4
@angular/cli                    10.1.6
@angular/material               10.2.4
@schematics/angular             10.1.6
@schematics/update              0.1001.6
rxjs                            6.6.3
typescript                      4.0.3

Metadata

Metadata

Assignees

Labels

P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: coreIssues related to the framework runtimecore: dynamic view creationstate: has PR

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions