Kerby82
Kerby82

Reputation: 5146

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.

Upvotes: 6

Views: 12168

Answers (3)

Amit Kumar
Amit Kumar

Reputation: 46

Navigating from one route to another route will always destroy current component and reload next component. In this case you render detail page from current component only by ngIf . I mean show and hide both template based on search. You will not need to change route, but that’s not a preferred solution.

However I would prefer to save data in common service and use the routing strategy.

Upvotes: 0

Peter Unger
Peter Unger

Reputation: 96

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.

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);
    }
  }
}

Upvotes: 8

Related Questions