Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override browser `back` button functionality in Angular?

I have a page in my Angular App where it uses a stepper. When the user is for example on step 3, the first logical thing he will do to get back to the previous step (step 2) is to click on the back button. But obviously, he will get redirected to the previous page.

So, I would be able to set the stepper to previous on back click instead of redirecting the user to last page and when he is on step 1 redirect him to last page.

I was trying to use @HostListener by casting this.stepper.previous(); (function which set the stepper to previous) but while the action is catched the function is not executed and the page is anyway redirected back.

So how can i prevent the page to get redirected on back button click?

Here is what I've tried:

@HostListener( 'window: popstate', ['$event'])
onPopState(event: Event): void {
  event.preventDefault();
  console.log("BACK PRESSED")
  this.stepper.previous();
}
like image 787
Kasper Juner Avatar asked Sep 15 '20 15:09

Kasper Juner


People also ask

How to prevent browser back button angular?

Run your application by typing the ng serve or ng build commands in your command line or terminal, and see the results: The browser back button will be disabled for whole the application.

How to disable back button after login in angular?

To prevent browse back navigation we make use of History. pushState() web api. As soon as the user lands on the component where we want to disable back navigation, we set history. pushState(null, '') .

What is browser back button?

A back button in the browser lets you back-up to the copies of pages you visited previously. The web browser's back and next buttons work well with web sites that provide information that changes infrequently, such as news and shopping web sites.


Video Answer


1 Answers

There two points here in your question:

  1. If you want disable back button for whole application or more than one component
  2. If you want just disable back button for a specific component

For the #1 requirement, I think the better way is to implement a Guard and apply it on the required routes. But, if the #2 is desired, using onPopState() looks OK, but it seems that you missed using LocationStrategy and history.pushState(), So try this:

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

@Component({
  selector: 'app-root'
})
export class AppComponent {
  constructor(
    private location: LocationStrategy
  ) {
    history.pushState(null, null, window.location.href);
    // check if back or forward button is pressed.
    this.location.onPopState(() => {
        history.pushState(null, null, window.location.href);
        this.stepper.previous();
    });
  }
}
like image 133
ng-hobby Avatar answered Sep 28 '22 05:09

ng-hobby