Angular - How to keep loaded content of a page/component when jumping between different routes using routing-outlet

I recently had to redirect between some components in an Angular application and I figured it would be a better user experience if the state was kept when navigating. So if you went back to the previous component you would be presented with the component as you left it. Per default when using the router (routing-outlet) what is on the page you navigate from is lost, which makes sense as it could be seen as a "page refresh".

I thought it would be a simple bool or setting I would have to set on the router in order for this to work, however it turned out to be much more trickier than that. I ended up using the routerreusestrategy as I wanted to keep the component as it was and make it a setting on which routes to "remember". I will include some other solutions that I took a look at.

Using routerreusestrategy

The RouteReuseStrategy makes it possible to achieve exactly what I wanted. It is a way to "cache" routes so that you can return to the page/component just as you left it. I ended up using the solution from You need to define your own RouteReuseStrategy where you can configure which routes should be "cached". This way you do not have to change anything in your components. I would have hoped this was built into Angular and if you know an easier way, please let me know in the comments down below.

Using a service

A simple way to keep state between pages is to keep it in a service. You likely already have a service for your component, you can find an example on how to do this here.

Using state object

Alternatively from Angular 7.2 you can use NavigationExtras when navigating between routes to provide some extra information (state). See this post on on how to do this.

That is it

I hope you found these 3 options for keeping state between navigations in Angular helpful. Feel free to leave a comment down below.