'Angular 2 - Does ngOnDestroy get called on refresh or just when navigate away from component?
I am trying to figure out if ngOnDestroy in Angular 2 gets ran on a refresh or just when someone navigates away from the page?
Solution 1:[1]
On refresh or when you navigate away from the current page (except for routing), then ngOnDestroy
won't be called. The application will just be destroyed by the browser.
Only when Angular2 removes the component from the DOM because you move away or you call destroy()
on a dynamically created component, then ngOnDestroy()
is called.
You can listen to beforeunload
and unload
yourself if you need some action to happen before the application is destroyed by the browser.
See also
Solution 2:[2]
You can do one thing and it works like a charm. Create a test guard and apply on your component.
Create a service with a BehavioralSubject. and whenever go to your component the guard will check and in the guard initialize your subject, as and when it gets initialized it will check if it is getting subscribed somewhere. In your component in the ngOnInit subscribe to this subject and from there call the destroy method.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jnr |
Solution 2 | Abhishek gupta |