Generated back button click event

Hi. I’m trying to log the user’s action of clicking the generated back button in the navigation bar, but I can’t find handle the click event?

it seems like the ion-nav-back-button from here isn’t working anymore?

That was for V1. Ionic 2 handles this differently, not allowing for customization.

Hi, so is there currently a way to handle the click event in V2?

If all you need is to handle when you leave the page you can use the lifecycle event ionViewWillLeave. Here’s the documentation.

Just put this function in your component:
ionViewWillLeave() {
console.log(“Looks like I’m about to leave :(”);
}

2 Likes

How then does the ion-navbar backButtonClick() instance member work?

http://ionicframework.com/docs/api/components/navbar/Navbar/#backButtonClick

For example on your page.html

<ion-navbar #navbar color="primary">
    <ion-title>Whatever</ion-title>
    <ion-buttons right>
      <button icon-only ion-button>
        <ion-icon name='pause'></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>

Note that the navbar is declared using #navbar id.
Then on your page.ts, you supposed to do this, to retrieve the navbar element

import { NavController, NavParams, Navbar } from 'ionic-angular';
.
.
.
.
export class Page {

@ViewChild('navbar') navBar: Navbar;

}

and next you can use it as you want:

ionViewDidEnter() {
    this.navBar.backButtonClick = () => {
      ///here you can do wathever you want to replace the backbutton event
    };

  }

Hope, it helps.

11 Likes

Great solution which worked well for me thanks @fredDS

Im not sure it was necessary, but also added changes to hardware back button to perform the same action(s)

@ViewChild('navbar') navBar: Navbar;

constructor(private platform: Platform) {
  this.platform.registerBackButtonAction(() => this.backButtonClick, 2)
}

backButtonClick() {
  console.log('// dos omething')
}

ionViewDidEnter() {
  this.navBar.backButtonClick = this.backButtonClick;
}

3 Likes

@ViewChild(Navbar) navBar: Navbar;

ionViewDidLoad() {
this.navBar.backButtonClick = (ev:UIEvent) => {
alert(‘this will work in Ionic 3+’);
}
}

2 Likes

Thank you for saving my time. It’s working on ionic 3. Cheers!!

this is right solution but there error will occur if u put the ‘navbar’ what u have to do is

 @ViewChild(Navbar) navBar: Navbar;

 
  ionViewDidLoad() {
    this.navBar.backButtonClick = (e:UIEvent)=>{
     // console.log("in");

      this.backbutton()  };
}

if u notice i removed the ‘’ from the @ViewChild(‘navbar’) where i became @ViewChild(Navbar) navBar: Navbar;

2 Likes