使用左侧窗口开发一个角度应用程序,我们的大多数用户发现,当他们按下移动设备的BACK按钮或左侧SWIPE时,通常关闭此sidenav。
对于左侧滑动,这是正常的(使用md-swipe-right = ...)。但是我对使用BACK按钮一无所知。有一个很好的方法吗?应该如何捕捉和阻止位置变更事件(或类似的事情)?
答案 0 :(得分:2)
供以后参考:
我发现的一种方法是在打开 sidenav 时将假状态推送到导航器的历史记录中,并在没有按下后退按钮而是定期关闭的情况下将其删除。如果按下后退按钮,那么假状态将随着按下按钮时触发的 back() 事件自动消失。
然后通过 sidenav 上的指令收听名为 '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