Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When exactly is component destroyed?

In Angular 2 with Ahead-of-Time (AOT) compiling, I have a parent component and a child component, like this:

<div>     <h1>I am a parent</h1>     <myChild *ngIf="showChild"></myChild> </div> 

I know that the child template is inserted to the DOM dynamically.

If showChild is evaluated to false, when exactly does Angular destroy the child component? Or will Angular destroy the child component at all? Is that the time Angular invokes the onDestroy() method?

like image 516
gye Avatar asked Apr 06 '17 15:04

gye


People also ask

When an angular component is destroyed?

The content is likely still applicable for all Angular 2 + versions. When an Angular component is destroyed, the ngOnDestroy life cycle method is called so we can clean up long-running tasks or unsubscribe from any RxJS Observables. Angular Services also have an ngOnDestroy method, just like Angular components.

How do you destroy components?

The ComponentRef of the newly created component and call the clear() method of ViewContainerRef destroys the existing view in the container. Add the destroy component. When we need to dynamically remove the component need to be please refer to the below clear function. Please follow the app.

Can we destroy a component in angular?

No, you can't do that, it's a lifecycle hook that is called when angular destroys the component by itself. You can use the ngIf directive in the component and update the value in the directive using service.

Does ngIf destroy component?

Angular's ngIf directive does not simply hide and show. It creates and destroys an HTML element based on the result of a JavaScript expression.


1 Answers

When Angular runs change detection and the binding to the ngIf input of the NgIf directive is updated, NgIf removes the component from the DOM. After the component is removed from the DOM ngDestroy() is called and then the component is free to get garbage collected.

If the parent component is removed while the *ngIf expression is true, the parent and child will be destroyed together. I don't know what ngDestroy() is called first though.

like image 159
Günter Zöchbauer Avatar answered Sep 22 '22 08:09

Günter Zöchbauer