Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular navigate back without reloading the page

I have a page on which the user can apply some filters (through a form) then the user can choose one of the element filtered and go to a detail page.

If the user click back on the detail page is been redirected to the filter page. The filter page is reloaded without keeping the filters data.

I use history.back() function for the back action.

I was wondering if there is a way to navigate back to a page without reloading it showing the exact page that was shown before the user click on details link.

like image 764
Kerby82 Avatar asked Sep 21 '18 14:09

Kerby82


1 Answers

The problem is, that your filter-page component gets destroyed on navigate, and therefore the component state will be lost. You have serveral options to maintain the filter state.

  • Use localstorage API to serialize and later retrieve the filterstate
  • Use a state management framework like ngrx or ngxs
  • Use a service to keep the filter state
  • Pass the state via activatedRoute

I would suggest to either use the localStorage API to save the state in a serialized way to the browser and retrieve it back on fiter-page init or saving the state of the filter into a service and request the state from there.

Here's a very basic example for the localStorage. (Not sure if the code is perfectly valid, but you should get the idea..)

export class FilterPage implements OnInit, OnDestroy {

  private filterItems: string[];

  constructor() { }

  ngOnInit() {
    if (localStorage.getItem('filterItems'))
      this.filterItems = JSON.parse(localStorage.getItem('filterItems'));
    } else {
      this.filterItems = [];
    }
  }
  
  ngOnDestroy() {
    if(this.filterItems.length > 0) {
      localStorage.setItem('filterItems', JSON.stringify(this.filterItems));
    }
  }
  
  addFilterItem(item: string) {
    if (!this.filterItems.includes(item)) {
      this.filterItems = [...this.filterItems, item];
    }
  }
  
  removeFilterItem(item: string) {
    if (this.filterItems.includes(item)) {
      this.filterItems = this.fiterItems.filter(currentItem => currentItem !== item);
    }
  }
}
like image 141
Peter Unger Avatar answered Oct 03 '22 19:10

Peter Unger