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
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).