Categories
Angular Answers

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

Spread the love

Sometimes, we want to detect back button press using router and location.go() with Angular and TypeScript.

In this article, we’ll look at how to detect back button press using router and location.go() with Angular and TypeScript.

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

To detect back button press using router and location.go() with Angular and TypeScript, we can listen to the popstate event.

For instance, we write

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

//...
export class AppComponent {
  //...
  @HostListener("window:popstate", ["$event"])
  onPopState(event) {
    console.log("Back button pressed");
  }
  //...
}

to use HostListener to listen to the window popstate event.

We set onPopState as the event’s handler.

event has the native event object.

Conclusion

To detect back button press using router and location.go() with Angular and TypeScript, we can listen to the popstate event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *