52

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.

6 Answers 6

46

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!');

    });

}

(...)
6
  • How to import this in my app.module. Anywhere I put this class I got an error.
    – MrD
    Jan 18, 2017 at 11:26
  • 12
    Angular documentation says not to use PlatformLocation directly, use Location instead.
    – dream_team
    May 8, 2017 at 16:26
  • 1
    How do you unsubscribe from this listener? Jul 31, 2017 at 22:10
  • 1
    @KevinLeStarge you don't. You should use Location instead as suggested by thorin87 Oct 20, 2017 at 9:48
  • 4
    you console.log('pressed back!') but it will be triggered by the forward button as well
    – Julien
    Oct 3, 2018 at 10:55
44

IMO better method of listenting for popstate events is to subscribe to location service

import {Location} from "@angular/common";

constructor(private location: Location) { }

ngOnInit() {
    this.location.subscribe(x => console.log(x));
}

It doesn't use PlatformLocation directly (as documentation suggest) and you can unsubscribe any time you want.

8
  • 8
    Don't forget to unsubscribe in ngOnDestroy() ! Sep 13, 2017 at 9:30
  • 2
    As an alternative you could subscribe to route.params.subscribe(...); Difference is that it will already fire when you initial enter the page, which location.subscribe(...) doesn't. The latter only fires when the parameter actually has changed. Sep 13, 2017 at 9:37
  • 1
    @Humppakäräjät how does that help to tell if user navigated back or not? There is no access to the history api in route..
    – Mackelito
    Nov 28, 2017 at 8:41
  • @Mackelito yes you are right it won't directly detect if he went back or forth. It only fires when it has detected that the route parameters have changed, which might happen when the user hits the browsers back or forth button. Nov 28, 2017 at 13:30
  • 2
    @Humppakäräjät It only fires when it has detected that the route parameters have changed, which might happen when the user hits the browsers back or forth button. - so as it only might work it is useless. Jul 27, 2018 at 8:42
25
import { HostListener } from '@angular/core';

and then listen for popstate on the window object:

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

This code works for me on latest Angular 2.

3
  • 9
    This doesn't work for me. No event is being triggered when the back button is clicked in this case. Oct 5, 2017 at 6:41
  • It's working fine on ng-version="5.2.9". It is simply awesome!
    – S Kumar
    Nov 14, 2018 at 13:15
  • 9
    how do you determine if it is triggered by a back or forward ? Feb 21, 2019 at 3:43
4

As thorin87 answer dont use PlatformLocation. We need subscribe an unsubscribe.

import {Subscription} from 'rxjs/Subscription';    

ngOnInit() {
  this.subscription = <Subscription>this
    .location
    .subscribe(() => x => console.log(x));
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}
0
4

in angular 8+

constructor(private readonly route: Router) {
this.route.events
  .pipe(filter((event) => event instanceof NavigationStart))
  .subscribe((event: NavigationStart) => {
    if (event.restoredState) {
      this.isBackUrl = true;
    }
  });

}

1
  • 1
    This doesn't check whether the navigation was back or forward.
    – paddotk
    Oct 30, 2020 at 13:44
-2

This solution works for all versions of Angular.

import { PlatformLocation } from'@angular/common';

constructor( private _location: PlatformLocation ) {

this._location.onPopState (() => {
 `enter code here` // You could write code to display a custom pop-up here.

 // window.location.href = 'https://www.google.com'; //Navigate to another location when the browser back is clicked.


});
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.