Header navigation back button custom action

I am aware this is against best practice, but I want to see how it feels.
I have a page with multiple stages, and when people wanna go back a stage, they naturally press the navigation back button, which exists the page.

I was wondering, if there is any way to make a global custom function for that back button? (like we can do for hardware back button on Android using Platform)

You could do something like this

ionViewCanLeave() {
	return new Promise((resolve, reject) => {
		if(at the first stage) {
			resolve();
		} else {
			go back a stage
			reject("going back a stage");
		}
	});
}
1 Like

Extremely helpful! Thanks

@mich356c That solution really helped.
I did:

ionViewCanLeave() {
    return new Promise((resolve, reject) => {
        if (this.activeStep === 0)
            resolve();
        else {
            this.slidePrev();
            reject("going back a stage");
        }
    });
}

And it works great when I want to go back. However, when I want to push a page over it, after completing all of the steps (in step 3), it rejects.
Is there a way to reject only back action but not forward action? (pushing new pages)

I suppose you would need to have something like “this.submitted” default to false, and when they submit it gets set to true. Then check if its true in the canLeave, and if so then resolve.

if(this.activeStep === 0 || this.dubmitted)
    resolve()

If you to go this route, you don’t just need to start wrapping stuff in promises, just return true or false:

ionViewCanLeave() {
  const canLeave = this.activeStep === 0;
  if (!canLeave) this.slidePrev();
  
  return canLeave;
}

Alternatively, you could get a little tricky and override the back button click instance method: https://ionicframework.com/docs/v2/api/components/navbar/Navbar/#backButtonClick

ionViewDidEnter() {
    if (this.activeStep === 0) {
      this.navbar.backButtonClick = () => this.navCtrl.Pop();
    } else {
      this.navbar.backButtonClick = () => this.slidePrev();
    }
}

That would fix you not being able to go forward.

2 Likes

@rlouie pretty neat your solution of overriding the backButtonClick :slight_smile:
I wanted to have a back action without animation on a specific page and your solution help me to achieve it, thx!