Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2+ | Remove forward history after browsing back

To be able to close my (dynamically added) modal with the browser back button, I am adding a #modal hash to my url once a modal opens. After the browser back button is pressed I listen to the pop state, check if there is a modal open and remove it. When the modal is closed without using the browser back button, I perform a history.back() and remove the modal. The side effect is that there is a forward path left in the history, which is the #modal hash.

Is there a way to get rid of this forward history?


I tried to navigate to the same URL after navigating back but this doesn't seem to do anything. I am also using queryParams in my app but I do not think this affects anything here.

When opening the modal, I add #modal:

this.router.navigate([], {fragment: 'modal', queryParamsHandling: 'merge'})

On pop state:

location.onPopState( () => {
  if(this.modalCount > 0){
    this.removeAllModals();
    const routerSub = this.router.events.subscribe(event => {
      if(event instanceof NavigationEnd) {
        this.router.navigate([], {replaceUrl:true, queryParamsHandling: 'merge';
        routerSub.unsubscribe();
      }
    })
  }
})
like image 963
kingofbbq Avatar asked May 02 '26 09:05

kingofbbq


1 Answers

Use

navigateByUrl()

Navigate based on the provided url. This navigation is always absolute.

It will replace the entire Url by defined path

location.onPopState( () => {
  if(this.modalCount > 0){
    this.removeAllModals();
    this.router.events.subscribe(event => {
      if(event instanceof NavigationEnd) {
        this.router.navigateByUrl('');         
      }
    })
  }
})
like image 108
Chellappan வ Avatar answered May 05 '26 01:05

Chellappan வ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!