Skip to content
Advertisement

Angular 2 How to detect back button press using router and location.go()?

I have built an app that uses router 3.0.0-beta.1 to switch between app sections. I also use location.go() to emulate the switch between subsections of the same page. I used <base href="/"> and a few URL rewrite rules in order to redirect all routes to index.html in case of page refresh. This allows the router to receive the requested subsection as a URL param. Basically I have managed to avoid using the HashLocationStrategy.

routes.ts

export const routes: RouterConfig = [
    {
        path: '',
        redirectTo: '/catalog',
        pathMatch: 'full'
    },
    {
        path: 'catalog',
        component: CatalogComponent
    },
    {
        path: 'catalog/:topCategory',
        component: CatalogComponent
    },
    {
        path: 'summary',
        component: SummaryComponent
    }
];

If I click on a subsection in the navigation bar 2 things happen:

  • logation.go() updates the URL with the necessary string in order to indicate the current subsection
  • A custom scrollTo() animation scrolls the page at the top of the requested subsection.

If I refresh the page I am using the previously defined route and extract the necessary parameter to restore scroll to the requested subsection.

this._activatedRoute.params
    .map(params => params['topCategory'])
    .subscribe(topCategory => {
        if (typeof topCategory !== 'undefined' &&
            topCategory !== null
        ) {
            self.UiState.startArrowWasDismised = true;
            self.UiState.selectedTopCategory = topCategory;
        }
    });

All works fine except when I click the back button. If previous page was a different section, the app router behaves as expected. However if the previous page/url was a subsection, the url changes to the previous one, but nothing happens in the UI. How can I detect if the back button was pressed in order to invoke the scrollTo() function to do it’s job again?

Most answers I saw relly on the event onhashchange, but this event does not get fired in my app since I have no hash in the URL afterall…

Advertisement

Answer

I don’t know if the other answers are dated, but neither of them worked well for me in Angular 7. What I did was add an Angular event listener by importing it into my component:

import { HostListener } from '@angular/core';

and then listening for popstate on the window object (as Adrian recommended):

  @HostListener('window:popstate', ['$event'])
  onPopState(event) {
    console.log('Back button pressed');
  }

This worked for me.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement