Dimitar Atanasov
Dimitar Atanasov

Reputation: 19

Is there a way to display the previous state of a component in Angular 2+? (NOT CHANGING THE ROUTE)

I have a component in which I am displaying different tables depending on variable state. I am curious if there is a way to display the previous state of the component when I click the "back button" in the browser.

Upvotes: 1

Views: 89

Answers (2)

Wojciech K
Wojciech K

Reputation: 1051

Store the variable in query parameters.

Every time the variable changes, change the query parameters:

constructor(
    private route: ActivatedRoute,
    private router: Router
) { }

changeParam(newValue: string) {
    this.router.navigate([], {
        relativeTo: this.route,
        queryParams: { yourParamName: newValue }
    });
}

This will push the new URL to browser's history, but it will reuse the route and it will not reload the whole page. Your current variable value will be available in the query parameters.


If you use other query parameters in that route, add queryParamsHandling: 'merge' option to ensure they are not removed:

this.router.navigate([], {
    relativeTo: this.route,
    queryParams: { yourParamName: newValue },
    queryParamsHandling: 'merge'
});

Read Router documentation and RouteReuseStrategy documentation for all available options.


If changing route query parameters is not acceptable to you, there is no way to achieve that behavior with the 'back' button in the browser (to the best of my knowledge).

Upvotes: 2

trisek
trisek

Reputation: 789

Only way how to do it is using something like NgRx.

Upvotes: -1

Related Questions