0

Is there any way to persist the view of a page in angular so that as a User I can get the same view when I revisit the same route.

For eg. RouteA has a search bar and when user search something it loads results below, now if user has searched something on that page and after that he leave that page and move to RouteB for some other operation. When he will revisit the page it should have the same view, that is searched term in the search bar and loaded data in the grid.

user1264429
  • 179
  • 2
  • 11

1 Answers1

0

For your use case, you can save the FormGroup instance before the user navigates to a different route.

if (this.searchFormGroup.valid) {
      this.searchService.setLastSearch(this.searchFormGroup);
}

where the definition for setLastSearch could be like

 setLastSearch(searchFormGroup) {
    this.lastSearch = searchFormGroup;
  }

And when the user revisits the page, in the ngOnInit method check if there is already a saved search(the formGroup instance you saved before navigating).

this.lastSearch = this.searchService.getLastSearch();

. If the answer is yes use the patchValue to populate the current formGroup instance. Something like below

if (this.lastSearch) {
 this.patchLastSearchedValue();
}

where the code for patchLastSearchedValue could be like

  patchLastSearchedValue(): void {
    Object.keys(this.lastSearch.value).forEach(name => {
      this.searchFormGroup.controls[name].patchValue(
        this.lastSearch.controls[name].value
      );
    });
  }
Rahul Singh
  • 690
  • 1
  • 5
  • 10
  • That was just one example how would this can be achieved in entire application at any level. To get the same snapshot of the view as you browse through different urls. – user1264429 Sep 19 '20 at 06:39
  • Refer this https://stackoverflow.com/questions/45290062/how-can-we-save-state-of-component-in-angular-2 – Rahul Singh Sep 19 '20 at 15:18