How can I handle the back button action on Ionic 2?
I want to be able to know what to do depending on which page is being shown to the user.
I didn't find a good answer to this question, but after a while I figured it out myself a way to do it. I'm gonna share with you all.
Thanks
In Ionic 3 Lazy Loading, I never felt the need of Handling back behavior of browser where as for platform.is('cordova') I have created following method which handles all back scenarios:
As per Ionic 2 RC.4 documentation from here:
You can use
registerBackButtonAction(callback, priority)
method ofPlatform
API to register the action on back button press.The back button event is triggered when the user presses the native platform’s back button, also referred to as the “hardware” back button. This event is only used within Cordova apps running on Android and Windows platforms. This event is not fired on iOS since iOS doesn’t come with a hardware back button in the same sense an Android or Windows device does.
Registering a hardware back button action and setting a priority allows apps to control which action should be called when the hardware back button is pressed. This method decides which of the registered back button actions has the highest priority and should be called.
Parameters :
Returns: Function : A function that, when called, will un-register the back button action.
I have Researched Many Things for back button handle Finally I Found a Good Solution for ionic latest Version 3.xx
Here's how I did it:
In every Page component, I created a function called
backButtonAction()
, which will execute custom code for every page.Code:
And in the
app.component.ts
, I used theplatform.registerBackButtonAction
method to register a callback that will be called everytime the back button is clicked. Inside it I check if the functionbackButtonAction
exists in the current page and call it, if it doesn't exists, just go to the main/first tab.One could simplify this if they didn't need to perform customized actions for every page. You could just pop or exit the app.
I did it this way because I needed to check if the modal was open on this particular page.
Code:
if the current page is the first tab, the app closes (as defined in the
backButtonAction
method).I used answers from here and other sources to accomplish what I needed. I noticed that when you build the application for production (--prod) this approach doesn't work, because of JS uglifying and simplifying:
Because of that, I use next in the "if" statement:
So the final code looks like this:
That's it! No need to add extra code on every page!