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

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.

Leave a Comment