Alert user upon clicking back (Ionic 2)


#1

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

How can I accomplish this?

Thanks


#2

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){}})

#3

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.


#4

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


#5

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


#6

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


#7

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?


#8

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>
        Back
    </button>
</ion-buttons>

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


#9

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.


#10

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.