Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 894
Adrian Moisa Avatar asked Aug 24 '16 20:08

Adrian Moisa


People also ask

What is NavigationStart in angular?

The Angular Routers triggers several events starting with when the Navigation starts ( NavigationStart ) and also when the Navigation end ( NavigationEnd ) successfully. It is triggered when the navigation is canceled either by the user ( NavigationCancel ) or due to an error in the navigation ( NavigationError).

Can we add routerLink to button?

Using Router links After Angular v4 we can directly add a routerLink attribute on the anchor tag or button.

Which angular package is used to route to URL?

Generate an application with routing enabledlink The following command uses the Angular CLI to generate a basic Angular application with an application routing module, called AppRoutingModule , which is an NgModule where you can configure your routes.


2 Answers

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.

like image 127
VSO Avatar answered Oct 05 '22 18:10

VSO


Another alternative for this issue would be to subscribe to the events emitted by the Angular Router service. Since we are dealing with routing, it seems to me that using Router events makes more sense.

constructor(router: Router) {     router.events       .subscribe((event: NavigationStart) => {         if (event.navigationTrigger === 'popstate') {           // Perform actions         }       }); } 

I would like to note that popstate happens when pressing back and forward on the browser. So in order to do this efficiently, you would have to find a way to determine which one is occurring. For me, that was just using the event object of type NavigationStart which gives information about where the user is coming from and where they are going to.

like image 27
Jon Black Avatar answered Oct 05 '22 17:10

Jon Black