This a very straightforward use case and I’m sure many Ionic developers would face it sooner or later but there is no sample or example about this.
Basically, I need to show an alert (using AlertController) to the user when taps on the Back button (or any other way to leave the current page) and ask for confirmation when there is unsaved data on the page.
I’m trying to use the result of AlertController’s buttons selection in ionViewCanLeave method but can’t make it work. Has anybody solved this problem already?
Updated with simpler, more self-contained answer that could very easily be moved into a service for reuse
Pretty straightforward, I’d think yes you’d want to use viewCanLeave here. It would be nice if the AlertController would resolve a promise with the button pressed when it was closed, that way you could treat it sort of like a regular confirm() dialog. Since it doesn’t, wrapped it in a function that does:
Thank you rlouie. Your solution works perfect. I just needed to change const canLeave = new Promise(...
to const canLeave = new Promise<Boolean>(...
to stop type check error.
As you said, I hope Ionic team make this change and have AlertController to resolve with the value passed by selected button.