Akash Chaudhary
Akash Chaudhary

Reputation: 711

How to override hardware back button action in Ionic 3?

I want to know which function is called when we click ion-navbar back button by default in ionic 3. I want to call the same function on hardware back button click.

Upvotes: 3

Views: 1864

Answers (1)

Sudarshana Dayananda
Sudarshana Dayananda

Reputation: 5265

You can use registerBackButtonAction of Platform Service. You can override hardware back button action as below inside app.component.ts. Remember to call registerBackButtonAction after Platform.ready().

import { Platform, App } from 'ionic-angular';

@Component({
  templateUrl: 'app.html'

})
export class MyApp {

  constructor(public platform: Platform, private app: App) {

    this.platform.ready().then(() => {

      this.platform.registerBackButtonAction(() => {

          let nav = this.app.getActiveNav()

          if (nav.canGoBack()) {
            // If there are pages in navigation stack go one page back
            // You can change this according to your requirement
            nav.pop();

          } else {

            // If there are no pages in navigation stack you can show a message to app user
            console.log("You cannot go back");
            // Or else you can exit from the app
            this.platform.exitApp();
          }
      });
    });
  }
}

Hope this will help you.

Upvotes: 6

Related Questions