简体   繁体   中英

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

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.

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.

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

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

I use a service for this purpose, saving and restoring the state of the page from an object stored in the service but i haven't been able to figure out how persist the result of a user file upload where i am holding a user uploaded image Pending file upload to cloud storage. Any ideas on solving this helpful as it seems like the cached file is cleared by angular navigation process

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM