Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Routing - keeping state of component when route changes [duplicate]

Tags:

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?

like image 581
Jarek Avatar asked Nov 26 '15 13:11

Jarek


People also ask

Is ngOnDestroy called on route change?

ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.

What is difference between routerLink and routerLink?

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.

How does Angular determine routing change?

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.


2 Answers

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.

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

Günter Zöchbauer


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.

like image 43
kernix Avatar answered Sep 28 '22 08:09

kernix