我创建的配置文件组件看起来像弹出窗口。该组件可以显示在每个页面上(它不依赖于路由)。我想关闭它是一个" back"智能手机上的按钮,所以我在窗口使用 HostListener 注释:popstate 。它工作,但如果我单击后退按钮ProfileComponent正在关闭,但浏览器也会转到上一页。我尝试使用 preventDefault():
来解决这个问题@HostListener('window:popstate', ['$event'])
@HostListener('window:keydown.escape')
closeProfile(event?: any) {
if(event) {
event.preventDefault();
}
this.store.dispatch(new layoutActions.CloseProfileAction());
}
但仍然无法运作。有没有办法覆盖后退按钮操作?
答案 0 :(得分:0)
popstate事件不可取消(如此处所述:https://developer.mozilla.org/en-US/docs/Web/Events/popstate)。所以在这种情况下,preventDefault没有做任何事情。
但是如果你想留在页面上,几乎要阻止后退按钮,只需关闭配置文件弹出窗口,你可以执行以下操作。
@HostListener('window:popstate', ['$event'])
@HostListener('window:keydown.escape')
closeProfile(event?: any) {
history.go(1);
this.store.dispatch(new layoutActions.CloseProfileAction());
}
希望这有帮助。