Want to prevent Component recreation while routing in Angular 2

pd farhad picture pd farhad · Sep 29, 2016 · Viewed 8.5k times · Source

Let's say we have two routes Dashboard and Profile. Dashboard has dynamic tabs feature like Google spreadsheet. I want to do some interactions(build charts, visualizing some data) creating tabs in the Dashboard. Now, if I route to Profile and then route back to Dashboard, I want to see what was before in those tabs in Dashboard. It means, I want to maintain the state in the client side. AFAIK while routing between components, it recreates components. Is it possible to make spreadsheet like application while using angular 2 routing? I need to use routing because in my application I have to use LazyLoading feature.

So what should be the idea? I am new to angular 2.

Answer

Günter Zöchbauer picture Günter Zöchbauer · Sep 29, 2016

Currently components are reused only when only route parameters change while staying on the same route.

If the route is changed, event when the new route adds the same component, the component is recreated.

The preferred workaround is to keep the model in a shared service that stays alive during route changes and use the data from this service to restore the previous state of the component.

It was mentioned that there are plans to support custom reuse strategies with the router but no timeline when this will become available.

Update

Support for custom reuse strategy was added to Angular2.

See also