Triggering Backbutton actions in Ionic 3Just a heads-up

I need to capture the back button event before it triggers. Once the listener is activated, the back signal has already been sent.

This is my approach so far:

 document.addEventListener("backbutton", () => {
       console.log("[WARN] Back button pressed");
       console.log("Textbox value: " + this.inputValue);
       this.showConfirm();
       document.removeEventListener("backbutton");
     });

I don't want to lose the value of "this.inputValue". Unfortunately, in most cases, it's already lost by the time the event is triggered.

Answer №1

One of the requirements is to display an alert when leaving a particular page.

To achieve this, you can make use of NavGuards:

There are instances where developers need control over views entering and exiting. To facilitate this, NavController provides the methods ionViewCanEnter and ionViewCanLeave. These functions bear resemblance to Angular route guards but are better integrated with NavController.

// ...

ionViewCanLeave() {

if(this.inputValue) {
// Display the alert
this.presentConfirm();
}

// Page will be left if inputValue is null
return this.inputValue === null;
}

presentConfirm() {
let alert = this.alertCtrl.create({
title: 'Exit',
message: 'Do you want to exit?',
buttons: [
{
text: 'Cancel',
role: 'cancel'
},
{
text: 'Exit',
handler: () => {

// Allow user to exit from current page
this.inputValue = null;

// Navigate back to previous page
setTimeout(() => { this.navCtrl.pop(); }, 500);

}
}
]
});
alert.present();
}

Answer №2

Here is the method I used to customize the Back Button functionality:

constructor(public plt: Platform) {
    //Catch BackBTN Event
        plt.ready().then( ()=> {
          plt.registerBackButtonAction( ()=> {
            this.showConfirm();
          })
        });​
}

showConfirm() {
      let confirm = this.alertCtrl.create({
        title: this.confirm,
        message: this.confirm_msg,
        buttons: [
          {
            text: this.disagree,
            handler: () => {
              console.log("Saved changes");
              this.dismiss();
            }
          },
          {
            text: this.agree,
            handler: () => {
              console.log("Discard changes");
              this.viewCtrl.dismiss();
            }
          }
        ]
      });
      confirm.present();
    }
  }

This approach allows me to define a custom method for handling the Back Button.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to retrieving specific information from a JSON file in an Angular application

Struggling with handling this JSON file [ [ { "category": "Bags", "productData": [ { "id": 1000, "name": "Tro ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

What is the best way to implement pipes and incorporate reusable action buttons in a Mat-table component for maximum reusability?

I am seeking assistance in creating a reusable component for the Angular Material Mat-table. I have made progress on loading data from the parent component to the child component, as can be seen in StackBlitz, but I now want to apply pipes to the data bef ...

The issue of updating a GLSL uniform variable during an animation in three.js using TypeScript remains unresolved

Running a three.js TypeScript application, I developed custom GLSL shaders using the THREE.ShaderMaterial() class. Now, I aim to enhance my code by switching to the THREE.MeshStandardMaterial class. This is an entirely new experience for me, and despite e ...

I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database. This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following er ...

Every time I attempt to submit the login form on the Ionic and Angular page, instead of capturing the values of the form group, the page simply refreshes

Struggling with submitting the login form in Ionic and Angular? When attempting to submit, the page reloads instead of capturing the form group values. I am utilizing angular reactive forms and form builder within the ionic framework. Need assistance in id ...

Creating a customized Axios instance in Typescript can provide more flexibility and control over

I am looking to create an API with a customizable instance using Axios. Ideally, I want to be able to use a basic instance like this: api.get("url")... In addition, I would like to have the flexibility to add dynamic bodies and access them using something ...

What is causing the error message "may require a suitable loader" to appear when I add my TypeScript Node module to my Next.js application?

After developing a TypeScript node module and integrating it into my Next.js app, I encountered an error when attempting to run the app. Are you aware of any reason why this issue may be occurring? Please refer to the information provided below. Details a ...

Implementing automatic selection for MUI toggle buttons with dynamic data

By default, I needed to set the first toggle button as selected import * as React from "react"; import { Typography, ToggleButton, ToggleButtonGroup } from "@mui/material"; export default function ToggleButtons() { const dat ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

Changing the font family for a single element in Next.js

One unique aspect of my project is its global font, however there is one element that randomly pulls font families from a hosted URL. For example: https://*****.com/file/fonts/Parnian.ttf My page operates as a client-side rendered application (CSR). So, ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...

Navigating through different components within a single page

Each segment of my webpage is a distinct component, arranged consecutively while scrolling e.g.: <sectionA></sectionA> <sectionB></sectionB> <sectionC></sectionC> All the examples I've come across involve creating ...

The contents table remains fixed in the top right corner as you scroll

I have developed an Angular app with a table-of-contents component that only displays two items. The code for the script is as follows: ts import { Component, OnInit } from '@angular/core'; import { pdfDefaultOptions } from 'ngx-extended-p ...

Utilizing the dialogue feature within Angular 6

Situation: I am managing two sets of data in JSON format named customers and workers: customers: [ { "cusId": "01", "customerName": "Customer One", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...

Creating Dynamic Ionic Slides with Additional Slides Inserted Before and After

Hello, I am currently using ngFor to generate a set of 3 slides with the intention of starting in the middle so that I can smoothly slide left or right from the beginning. When I slide to the right, I can easily detect when the end is reached and add anot ...

Using ng-repeat with an AJAX-called JSON is not possible

I've been struggling with handling JSON data from an AJAX call and displaying it using ng-repeat. If you want to take a look at my code in a more organized way, I've shared it on http://jsfiddle.net/7quj9omw/. However, please note that the code ...