Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect user navigating back in Angular2?

I have a component and I need to detect if user pressed back button in his browser to navigate back.

Currently I'm subscribing router events.

constructor(private router: Router, private activatedRoute: ActivatedRoute) {      this.routerSubscription = router.events         .subscribe(event => {              // if (event.navigatesBack()) ...          });  } 

I know that I can use window.onpopstate but it feels like a hack when using Angular2.

like image 803
Michał Pietraszko Avatar asked Nov 02 '16 13:11

Michał Pietraszko


1 Answers


EDIT Please don't do this.

The official docs say "This class should not be used directly by an application developer. Instead, use Location." Ref: https://angular.io/api/common/PlatformLocation


It's possible to use PlatformLocation which has onPopState listener.

import { PlatformLocation } from '@angular/common'  (...)  constructor(location: PlatformLocation) {      location.onPopState(() => {          console.log('pressed back!');      });  }  (...) 
like image 124
Michał Pietraszko Avatar answered Oct 03 '22 23:10

Michał Pietraszko