13

Assuming I have two Angular 2 components: ComponentA and ComponentB. I want to be able to navigate from ComponentA to ComponentB and then eventually back to ComponentA, while not having to reinitialize ComponentA.

In the current Angular 2 Router implementation, every time I navigate away from a component, the component gets destroyed and has to be recreated the next time I navigate to it.

I know that I can preserve the state of components by using a Service, but this seems to be more like a workaround than an actual solution to my issue. Is there any way around this?

Gil Epshtain
  • 8,670
  • 7
  • 63
  • 89
Tudor Ciotlos
  • 1,805
  • 4
  • 29
  • 47
  • 1
    See the links in http://stackoverflow.com/questions/33940095/angular2-routing-keeping-state-of-component-when-route-changes/36010817#36010817 – Günter Zöchbauer Feb 16 '17 at 05:45
  • 1
    See also http://stackoverflow.com/questions/41280471/how-to-implement-routereusestrategy-shoulddetach-for-specific-routes-in-angular – yurzui Feb 16 '17 at 05:48
  • Hi Günter. Your link mentions `CanReuse` but I couldn't find it in the docs. Do you know if it still exists or if maybe it has been renamed? – AngularChef Feb 16 '17 at 09:18
  • @AngularFrance Apparently `CanReuse` was removed from the final version of Angular 2. To achieve a similar result, we can use the class `RouteReuseStrategy`, as also stated in the updated answer of Günter. – Tudor Ciotlos Feb 16 '17 at 10:27
  • Ha, thanks! The search field on angular.io didn't yield any results when searching "reuse" (not event `RouteReuseStrategy`) so I couldn't find it. – AngularChef Feb 16 '17 at 10:31
  • Does this answer your question? [How to implement RouteReuseStrategy shouldDetach for specific routes in Angular 2](https://stackoverflow.com/questions/41280471/how-to-implement-routereusestrategy-shoulddetach-for-specific-routes-in-angular) – satanTime May 17 '20 at 07:59

1 Answers1

1

Yes, it is, you need to implement RouteReuseStrategy.

and define a behavior for routes that reuse components.

Check more info in this answer: https://stackoverflow.com/a/41515648/13112018

satanTime
  • 12,631
  • 1
  • 25
  • 73