Alert user upon clicking back (Ionic 2)


I’d like to display an alert when the user clicks back if they haven’t saved.

How can I accomplish this?



i think you must init var save to false for exemple and when the user save the project turn it to true if user modify the project turn it again to false and display alert as like this :slight_smile:

$(window).unload(function(){var e=confirm("Are you sure you want to exit?");if(e){}})


One common suggestion is to listen for the back button click event, but I don’t like that idea because a user might find a way to leave a page “incorrectly” in a way I hadn’t predicted (not just via the back button). So on a page where nav flow is critical, I set a flag upon entry to false, and only set it to true if the user is leaving through one of the doors I intended to be opened. Then inside ionViewWillLeave() I check whether the flag is false, and handle the “bad” leave accordingly. You could set up a guard so the use can’t leave until your bad-leave handler gets confirmation that the user wants you to discard information.


How do I set up the guard to only trigger when the user pops to root?


How is the user going to pop to root? I don’t understand your question.


I mean, the user should be able to push and pop pages onto the navigation stack freely, unless the user is popping to the root page (by clicking back).


Why does the root matter? Or, maybe more important, why does the page have any view of anything except when the user enters or leaves?


The root matters because it is the parent of the page with the unsaved data. If the user pops to root, then their unsaved data will be lost.

I think I figured it out, though. I implemented a custom back button by putting this in the css for the page with potentially unsaved data:

button.back-button {
    display: none !important;

and this in the <ion-navbar> for the same page:

<ion-buttons left *ngIf="navCtrl.canGoBack()">
    <button ion-button icon-left (click)="clickBack()">
        <ion-icon name="arrow-back"></ion-icon>

Then I put the logic in a method called clickBack().


You test a flag in ionViewCanLeave(), and if the flag isn’t set to a way the user leaves that saves data, you present an alert asking the user to confirm they want to delete data, and the alert handler deletes the data and allows the user to leave if that’s what the user chooses.


I don’t really understand how that would work. I tried putting the logic in ionViewCanLeave(), but I couldn’t get it to trigger only when it was popping to the parent page.

The way I’m doing it now seems to work. Thanks for your help, though.