'Angular: Keep state of component on back navigation but also reset it
I'm new to Angular and have a requirement regarding routing between components. The app consists of 3 components:
component_a -> component _b -> component_c
In component_b there is a list which can be filtered and sorted. When I navigate from component_b to component_c (detail view) and back again (via browser back) the list should be filtered and sorted based on the already entered values.
However, if I navigate from component_a to component_b, the filters and sorters should be reset.
The filters and sorters are stored in a service, so they are read and applied again when navigating back from component_c to component_b.
To reset the filters/sorters when starting from component_a, a state is passed via the route, which triggers the reset.
component_a
this.router.navigate(["component_b"], {state: {reset: true}});
component_b
if (window.history.state?.reset) {
this.reset();
}
Unfortunately, the behavior is now also such that when from component_c is navigated back to component_b via browser back, this state is still present and the filters/sorters are incorrectly deleted.
I already tried it with adding the filters/sorters to the url as query params. But since the filters can get very complex, this solution is not practical for me.
How could I implement this requirement correctly?
Solution 1:[1]
- If component_a (when the parent component is component_a ) loaded before component_b, when navigating back from component_c to component_b , then state is passed to component_a. Then state will be lost when component_b is loading.
State is lost when reloading/loading another component before the navigation
If that's the case try to pass the state again from the component_a
Use
this.router.getCurrentNavigation().extras.state.resetto read the stateconstructor(private router: Router) { if(this.router.getCurrentNavigation() !== undefined) { if(this.router.getCurrentNavigation().extras !== undefined) { if(this.router.getCurrentNavigation().extras.state !== undefined) { if(this.router.getCurrentNavigation().extras.state.reset) { this.reset(); } } } } }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amandee Manushika |
