5

我的Angular应用程序中有一个页面,它使用stepper. 例如,当用户在第 3 步时,为了返回上一步(第 2 步),他要做的第一件合乎逻辑的事情是单击back button. 但显然,他会被重定向到上一页。

因此,我将能够stepper在返回单击时将其设置为上一个,而不是将用户重定向到最后一页,并且当他在第 1 步时将他重定向到最后一页。

我试图@HostListener通过强制转换this.stepper.previous();(将步进器设置为上一个的函数)来使用,但是当动作是catched该函数时,该函数没有被执行,并且页面无论如何都会被重定向回来。

那么如何防止页面在单击后退按钮时被重定向?

这是我尝试过的:

@HostListener( 'window: popstate', ['$event'])
onPopState(event: Event): void {
  event.preventDefault();
  console.log("BACK PRESSED")
  this.stepper.previous();
}
4

1 回答 1

5

你的问题有两点:

  1. 如果您想要disable back整个应用程序或多个组件的按钮
  2. 如果您只想要disable back特定组件的按钮

对于 #1 要求,我认为更好的方法是实现 aGuard并将其应用于 required routes。但是,如果需要 #2, usingonPopState()看起来不错,但似乎你错过了使用LocationStrategy and history.pushState(),所以试试这个:

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();
    });
  }
}
于 2020-09-15T15:51:43.453 回答