I have a view with a form and an ion-back-button. I’d like to show an alert box which warns the user that their changes will not be saved when they select the back button. If they choose to cancel, is it possible to cancel the navigation at that point?
Something like this…
ionViewWillLeave() {
if(this.formGroup.dirty) {
const alert = await this.alertController.create({
header: 'Confirm!',
message: 'If you navigate away from this page, your changes will not be saved. Please press "Save" to save your changes.',
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
// Cancel navigation
}
}, {
text: 'Okay',
}
]
});
await alert.present();
}
}
So you are using Ionic v3 correct?
So you can return a boolean that indicates if the user can Leave. As you show a Alert, which happens async try to return a Promise of a boolean like:
ionViewWillLeave(): Promise<boolean> {
return new Promise<boolean>(resolve => {
if(this.formGroup.dirty) {
const alert = await this.alertController.create({
header: 'Confirm!',
message: 'If you navigate away from this page, your changes will not be saved. Please press "Save" to save your changes.',
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
// Cancel navigation
resolve(false);
}
}, {
text: 'Okay',
handler: () => {
resolve(true);
}
}
]
});
await alert.present();
} else {
resolve(true);
}
});
}
Using v5, sorry that wasn’t clear.
Doesn’t look like this works with v5, navigation has already pretty much happened by the time the alert shows up.
If you are using v5, you should use Angular’s CanLeaveGuard. Check this out, this is exactly what you want.
1 Like
Exactly what I needed, thank you!