I have an application, with views behind routes, I need to be able to continue from the point when the route changed, but after going back, the component is in its initial state.
Is there any way how to keep the state of a component?
ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.
What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.
Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.
update 2
That's now fixed (Angular 2.3) for the new router by https://github.com/angular/angular/pull/13124 which allows to provide a custom reuse strategy.
For an example see also https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx
Angular docs https://angular.io/api/router/RouteReuseStrategy
update 2 This answer is only for a long ago discontinued router version.
See https://angular.io/docs/ts/latest/guide/router.html#!#guards for how to do it in the current router.
original
If your components implements CanReuse and returns true
from
routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) { return true; }
then the component is kept and reused instead of destroyed and recreated.
Another way is to keep the data in a shared service and fetch them from there when the component is recreated.
There is an open issue on this exact scenario in https://github.com/angular/angular/issues/5275
You can use routerCanReuse
only if the new component and the old component(when you hit the 'back' button) are of the same Component type.
As Günter suggested your only option right now if the Components are of different type is to keep state in a shared service.
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