Home > Mobile >  Is there a way to preserve DOM state of the component after navigating away and back in Angular
Is there a way to preserve DOM state of the component after navigating away and back in Angular

Time:03-11

After researching the issue for a few days I've seem to have reached a dead end.

I'm dealing with, what I assumed, was a fairly common scenario: After user navigates to a certain page and makes some changes (content of an input field, scroll through grid data or even changing some editable cell values ), he navigates to different page. When user returns to original page, all of the changes must remain the same.

Now, that means that cursor in the aforementioned input field must be in the same place, scroll position in the grid and changed cell values, as well as any other changes user made, must be preserved.

Solutions like storing data in localStorage, using services or even custom reuse strategy will not work, because saving that amount of information contained in multiple sub components will be impossible.

Currently, I'm considering DOM manipulation, where rendered template will be moved to a container in parent component in onDestroy hook, and returned later in onInit. That, of course, is a hail Mary attempt and feels very unnatural.

I'm hoping someone had (and solved) this problem before because, like I've mentioned, it seams like fairly common use pattern.

CodePudding user response:

There is not much option to do this in angular compared to React,

What I can recommend you is, store all the data in "environment" as object and when user routes back populate data from environment.

Usually I do this, when a component loads I store values in objects. When on destroy called all this objects goes to the environment under a one main object.

When oninit calls I am checking if object has values and restoring the page to where it was.

CodePudding user response:

I think you are looking for Angular RouteReuseStrategy, where Angular can cache some routes state, without destroying the component state, so when ever the user visit the same route a cached view will be used, RouteReuseStrategy Docs.

You can also check this medium article, implementing the required methods Medium

CodePudding user response:

for small amount data we can use services or localstorage as you mentioned for large amount data we can go with

NgRx

https://dzone.com/articles/angular-app-state-management-with-ngrx

  • Related