2017-02-27 43 views
2

如何在按下硬件後退按鈕時防止默認導航?我試過registerBackButtonAction,但是它覆蓋了我不想要的每個頁面中後退按鈕的行爲。Ionic 2防止硬件後退按鈕默認

這也沒有幫助。

document.addEventListener("backbutton", (event) => { 
     event.preventDefault(); 
    }, false); 

回答

8

正如你在Ionic docsregisterBackButtonAction回報看功能:

,調用它時,將註銷其後退按鈕 動作的功能。

所以,你可以使用該功能來恢復默認行爲,離開頁面的時候,像這樣:

import { Component} from '@angular/core'; 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 
export class HomePage { 

    // Property used to store the callback of the event handler to unsubscribe to it when leaving this page 
    public unregisterBackButtonAction: any; 

    constructor(...) { ... } 

    ionViewDidEnter() { 
     this.initializeBackButtonCustomHandler(); 
    } 

    ionViewWillLeave() { 
     // Unregister the custom back button action for this page 
     this.unregisterBackButtonAction && this.unregisterBackButtonAction(); 
    } 

    public initializeBackButtonCustomHandler(): void { 
     this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => { 
      this.customHandleBackButton(); 
     }, 10); 
    } 

    private customHandleBackButton(): void { 
     // do what you need to do here ... 
    } 
} 

因此,大家可以看到,關鍵是存儲registerBackButtonAction方法的回調稍後在離開頁面時使用它(或者當您想恢復默認行爲時):

this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => { 
    this.customHandleBackButton(); 
}, 10); 
+1

非常感謝!我曾想過如何將它存儲爲事件監聽器的序號處理程序,但我不知道如何在離開時取消註冊。 –

+0

很高興聽到它幫助:) – sebaferreras

+1

很想看到TypeScript版本相同 –