[英]Close angular modal and remain on same page on back button click
我正在使用 Angular 6 開發一個使用角度模態的 Web 應用程序。 在我的手機 (Android) 上,我注意到在模式打開時單擊手機的后退按鈕不僅會關閉打開的模式,還會導航回上一頁。 是否可以僅關閉打開的對話框並保留在主頁上? 我認為這將是手機上的預期行為。
謝謝!
@Simo,有點復雜。 在 Cordova 中,您有一個事件“deviceready”,可用於控制事件暫停、恢復和后退按鈕。
閱讀官方文檔以將 Web 應用程序轉換為 movil 應用程序。
您可以看到 Cordova 向“文檔”添加了新事件。 https://cordova.apache.org/docs/en/latest/cordova/events/events.html
那么如何將它添加到我們的 Angular 應用程序中?
對我來說,最好的方法是更改 AppComponent(主要組件)以添加新事件並使用服務使所有過程透明。
在 AppComponent(主要組件)的 AfterViewInit 中,我們將添加用於准備、暫停、恢復和后退按鈕的 document.addEventListener
//we use a enum for the different events.
export enum CordovaEvent {BackButton,Resume,Pause}
export class AppComponent implements AfterViewInit{
constructor(private cordovaEventService:CordovaEventService) { }
ngAfterViewInit() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
}
onDeviceReady() {
// Control pause, resume and backbutton
document.addEventListener('pause', this.onPause.bind(this), false);
document.addEventListener('resume', this.onResume.bind(this), false);
document.addEventListener("backbutton", this.onBackKeyDown.bind(this), false);
//a variable that I can use to know if is really a movil application
this.cordovaEventService.isCordoba=true;
};
onPause() {
//the only thing that I make is execute a function in a service
this.cordovaEventService.sendEvent(CordovaEvent.Pause);
};
onResume() {
this.cordovaEventService.sendEvent(CordovaEvent.Resume);
};
onBackKeyDown(e) {
this.cordovaEventService.sendEvent(CordovaEvent.BackButton);
e.preventDefault();
e.stopPropagation();
};
}
我們的服務非常簡單。 只是一個私有主題和一個可以訂閱我們組件的 Observable。
@Injectable()
export class CordovaEventService {
private listeningSource:Subject<CordovaEvent>=new Subject<CordovaEvent>();
cordovaEvent:Observable<CordovaEvent>=this.listeningSource.asObservable();
isCordoba:boolean=false;
constructor() {
}
sendEvent(evento:CordovaEvent)
{
this.listeningSource.next(evento);
}
}
最后,任何組件都可以在 ngOnInit 中訂閱 cordovaEvent
ngOnInit() {
this.cordovaEventService.cordovaEvent.subscribe((evento: CordovaEvent) => {
if (evento == CordovaEvent.BackButton) {
this.ngZone.run(()=>{
....make something...
})
}
});
}
我試過這個,它似乎工作
// push history state when a dialog is opened
dialogRef.afterOpened.subscribe((ref: MatDialogRef<any, any>) => {
window.history.pushState(ref.id, '');
// pop from history if dialog has not been closed with back button, and gurrent state is still ref.id
ref.afterClosed().subscribe(() => {
if (history.state === ref.id) {
window.history.go(-1);
}
});
});
嘗試這個
import { Router, Event } from '@angular/router';
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
$(".modal").modal('hide');
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.