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.