1

In my Angular application, users can configure settings on a particular page (e.g., filters, view preferences, etc.). When the user navigates to another route and then returns to the original page, I want to restore the previously selected settings.

What is the most efficient way to persist and restore these page-specific settings, aside from using localStorage or storing data in a shared service file? Is there a more Angular-native or optimized approach for this use case?

2 Answers 2

2

You can try to use the state property of the NavigationExtras type object that is passed to the router.navigate method for example

this.router.navigate(['/next-page'], { state: { filter: { employeeName: 'Adam', yearOfBirth: 1996 } } });

then in ngOnInit method you can retrieve the state that was pushed in the window.history and eventually pass it back as state when navigating back to the old route.

ngOnInit() {
  this.activatedRoute.paramMap.subscribe((params) => {
     if (window.history.state['filter']) {
        this.employeeFilter = window.history.state['filter'];
     }
   });
}

goBack(e: any) {
   this.router.navigate(['/previous-page'], { state: { filter: this.employeeFilter } });
}

This way you can pass data forth and back between components without using localStorage or sessionStorage and without relying on a root injected service to persist it.

More info about passing state on navigation using the Angular Router here

Sign up to request clarification or add additional context in comments.

Comments

1

You can opt to not destroy the route, using RouterReuseStrategy.

Boosting Angular App Performance with RouteReuseStrategy.

Use this for certain routes alone. Most of the time, destroying and recreating a component is a good thing because the initial state is returned and will prevent unnecessary bugs in your code due to state persistence.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.