Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override ion-back-button action in ionic 4 with angular 7

I wanted to stop navigation from one page to another page when user clicks on ion-back-button. I have some validation/check to be perform based on which app will decide whether to allow back action or not.

like image 241
Shubham Takode Avatar asked May 23 '19 10:05

Shubham Takode


2 Answers

Use IonBackButtonDelegate to override the functionality. Here's a simple example -

import { IonBackButtonDelegate } from '@ionic/angular';

...

export class TestPage {

  @ViewChild(IonBackButtonDelegate, { static: false }) backButton: IonBackButtonDelegate;

  ...
  // Registering
  ionViewDidEnter() {
    console.log('ionViewDidEnter');
    this.setUIBackButtonAction();
  }

  setUIBackButtonAction() {
    this.backButton.onClick = () => {
      // handle custom action here
    };
  }
}
like image 136
arif08 Avatar answered Sep 22 '22 17:09

arif08


This can be accomplished by Ionic Life Cyle Hooks

ionViewDidLoad: Fired only when a view is stored in memory. This event is NOT fired on entering a view that is already cached. It’s a nice place for init related tasks. ionViewWillEnter: It’s fired when entering a page, before it becomes the active one. Use it for tasks you want to do every time you enter in the view (setting event listeners, updating a table, etc.).

ionViewDidEnter: Fired when entering a page, after it becomes the active page. Quite similar to the previous one.

ionViewWillLeave: Fired when you leave a page, before it stops being the active one. Use it for things you need to run every time you are leaving a page (deactivate event listeners, etc.).

ionViewDidLeave: Fired when you leave a page, after it stops being the active one. Similar to the previous one.

ionViewWillUnload: Fired when a view is going to be completely removed (after leaving a non-cached view).

As a bonus track, there are two other powerful methods related to those events: nav guards. Those methods are focused on view access control (with authentication purposes).

Nav Guards If you wanted to prevent a user from leaving a view:

export class MyClass{
 constructor(
   public navCtrl: NavController
  ){}

  pushPage(){
    this.navCtrl.push(DetailPage);
  }

  ionViewCanLeave(): boolean{
   // here we can either return true or false
   // depending on if we want to leave this view
   if(isValid(randomValue)){
      return true;
    } else {
      return false;
    }
  }
} 

ionViewCanEnter: Fired before entering into a view, allows you to control whether the view can be accessed or not (returning true or false).

ionViewCanLeave: Fired before leaving a view, allows you to control whether the view can be left or not.

It is important to highlight that Nav Guards are executed before any other lifecycle event method.

like image 27
Ravikumar Avatar answered Sep 24 '22 17:09

Ravikumar