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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With