I am not able to figure out when does the angular decide to call onDestory event?
When I toggle the component with *ngIF
directive, onDestory is not called and the state of the component is maintained as if it is using the same instance of the component?
Can anybody elaborate as to when angular(2) destroys component? And how to achieve newer instance of component when toggling with *ngIf
?
Most DOM manipulations in Angular are performed using ViewContainerRef. In particular, this mechanism is used internally by ngIf
:
private _updateView() {
...
this._viewContainer.clear();
...
this._thenViewRef =
this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
}
}
and router-outlet:
@Directive({selector: 'router-outlet', exportAs: 'outlet'})
export class RouterOutlet implements OnDestroy, OnInit {
constructor(..., private location: ViewContainerRef, ...)
detach(): ComponentRef<any> {
...
this.location.detach();
...
}
attach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute) {
...
this.location.insert(ref.hostView);
}
Whenever either viewContainer.clear()
or viewContainer.remove(index)
method is called the relevant components or embedded views (created with ng-template
) are removed and ngOnDestroy
lifecycle hook is called on them.
Can anybody elaborate as to when angular(2) destroys component?
This will happen when using structural directives like ngIf
and ngFor
, when router navigates away from current router-outlet
directive or when you manually remove dynamic components or embedded views using viewContainerRef
.
You can read more about DOM manipulation using ViewContainerRef
in:
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