BeliliF
BeliliF

Reputation: 174

Ionic 2 customize back button action

I want to customize the click-action of the back button mentioned in this screen capture. I want that by clicking I do not return to the previous page but to a page that I specify myself, or do a treatment before going back.

screenshot

Upvotes: 7

Views: 5726

Answers (3)

Anand_5050
Anand_5050

Reputation: 1159

You need to just remove the current index from stack of ViewController

import { ViewController} from 'ionic-angular';

      constructor(public navCtrl: NavController, public viewCtrl: ViewController) {
      }


this.navCtrl.push("APage").then(() => {
      const index = this.viewCtrl.index;
      this.navCtrl.remove(index,1);
    });

Upvotes: 0

Ariel Antonio Fundora
Ariel Antonio Fundora

Reputation: 1488

For customize default back button action you need override the backButtonClick() method of the NavBar component.

Step 1: In your "custom-class.ts" import Navbar component. Create auxMethod for override the default behavior and called in your ionViewDidLoad method.

import { Navbar } from 'ionic-angular';
import { ViewChild } from '@angular/core';

export class myCustomClass {
    @ViewChild(Navbar) navBar: Navbar;

    ionViewDidLoad() {
        this.setBackButtonAction()
    }

    //Method to override the default back button action
    setBackButtonAction(){
       this.navBar.backButtonClick = () => {
       //Write here wherever you wanna do
          this.navCtrl.pop()
       }
    }
}

This code has been tested in ionic 3.

Upvotes: 14

Alexander Trakhimenok
Alexander Trakhimenok

Reputation: 6268

You can try to use ionViewCanLeave or ionViewWillLeave event.

See this issue #9533 with proposal to distinguish leave events for "back" navigation. This can be handy for your use case once implemented.

Upvotes: 0

Related Questions