I want to disable the hardware back button on dashboard page. Back button need to work on remaining pages for navigation purpose except on dashboard page. If hardware back button was used on dashboard page it need to show close message and if again click on hardware back button then it needs to be closed.
I’ve used the below code in app.component.ts . It disabling hardware back button completely even in before/after login too.
I’m unable to get page name. Please give suggestons if any. Thanks in advance.
To extend on @EinfachHans’s excellent answer, don’t do anything relying on string names of classes or properties (this includes “page name”). Ever. You will find “solutions” that will work during testing and then break mysteriously in production.
I had to do the subscription in the constructor method for the app to detect the subscription properly.
But since I had to enable the back button for child views and only disable the back button on the top parent view, I had to set a local boolean value according to whether I was in the parent view or not.
Here’s the solution that I did to make it work (in case somebody else might stumble upon this challenge):
private isCurrentView: boolean;
private displayWarning: boolean;
constructor(private platform: Platform) {
this.subscriptions.add(
this.platform.backButton.subscribeWithPriority(9999, (processNextHandler) => {
if (this.isCurrentView) {
this.displayWarning = true;
// Or other stuff that you want to do to warn the user.
} else {
processNextHandler();
}
})
}
ionViewDidEnter() {
this.isCurrentView = true;
}
ionViewWillLeave() {
this.isCurrentView = false;
}
I only execute the processNextHandler() if I am not in the parent view - this enables the native back button function.
this.subscriptions is a Subscription (from rxjs), where I add subscriptions onto that variable, so that I can unsubscribe all subscriptions contained in that variable when I leave the component (e.g. ngOnDestroy).
// Initialize the variable at the top of the component
const subscription = new Subscription();
// Inside any function
this.subscription.add(
// Add the subscription you want to execute here.
)
// When leaving the component / at the end of the component life cycle
this.subscription.unsubscribe();
I believe that it helps for better cleanup in the component life cycle so you won’t end up having too many subscriptions eating up processor memory.