开发带有左侧导航的 Angular 应用程序时,我们的大多数用户发现,当他们按下手机的“后退”按钮或向左滑动时,通常会关闭此侧导航。
对于向左滑动,这是可以的(使用 md-swipe-right=...)。但是我没有发现任何有关使用“后退”按钮的信息。有什么好的方法吗?应该如何捕获和阻止位置更改事件(或类似的事情)?
最佳答案
供将来引用:
我发现的一种方法是在打开侧导航时将假状态推送到导航器的历史记录中,并删除它,以防后退按钮没有被按下,而是定期关闭。如果按下后退按钮,则假状态将自动消失,并在按下按钮时触发 back() 事件。
然后监听名为“popstate”的后退按钮事件,并在侧导航上使用指令,您可以按照自己的意愿使用整个事件。
示例:
指令:
@Directive({
selector: '[CatchMobileBackEvent]'
})
...
sidebar: MatSidenav;
@Input('sidenavRef') set sidenavRef(sidenav: MatSidenav) { // get the sidebar ref
this.sidebar = sidenav;
}
@HostListener('window:popstate', ['$event']) onMobileBack(e) { // when back button pushed close sidenav (and it stays on the same page because the current history state is fake)
this.sidebar.close();
}
@HostListener('closed', ['$event']) checkIfClosedFromButton(e) { // listen to sidebar's closed event
if (history.state === 'sidebarOpened') { // it means the sidebar was closed not from the mobile back button
history.back(); // remove the fake history state
}
}
@HostListener('opened', ['$event']) pushFakeHistoryWhenOpened(e) { // listen to sidebar's opened event
if (this.isSmartphone$.getValue()) {
history.pushState('sidebarOpened', 'sidebarOpened'); // for mobile back button
}
}
在模板中:
<mat-sidenav
#sideNavMenu // declare the sidebar as a template variable so you can pass it to the directive
CatchMobileBackEvent // put the directive on the sidebar you want to control
[sidenavRef]="sideNavMenu"> // pass the sidebar ref to the directive
关于angularjs - Angular : how to close a sidenav with the BACK button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38330902/