Run a command to engage with the user and then display a new page

Currently, I'm exploring the documentation in search of a solution for the following scenario:

Imagine the user is on a form page and decides to go back. I want to prompt a verification message like

"Are you sure you want to discard your changes?"
. Depending on whether they click yes or no, a function will be executed before leaving the page.

I am aware that I can utilize

Platform.registerBackButtonAction()
to monitor when the hardware back button is clicked. However, how can I achieve similar functionality for the NavController back button located in the header?

While NavGuards are automatically integrated with the NavController back button, they execute the function after leaving the page, which does not align with my requirements.

Essentially, the desired flow is as follows:

Enter the page >> Enter information in any input field >> If attempting to leave the page, trigger a prompt alert >> Upon clicking 'yes', exit the page

Below is a snippet of the code I have been working on:

ionViewCanLeave() {
    let confirmationAlert = this.alerts.create({
        title: "Confirmation Message",
        buttons: [{
            text: 'Cancel',
            handler: () => {
                this.navCtrl.pop();
            }
        }, {
            text: 'Yes',
            handler: () => {
                this.saveDescription();
            }
        }]
    });

    if (this.changes != undefined && this.changes!= '') { 
        confirmationAlert.present();
    } else {
        this.navCtrl.pop(); 
    }
}

How can I implement this functionality? Is there a way to prevent users from leaving the view, perform an action, and based on the outcome, decide whether to exit?

Thank you :)

Answer №1

How about trying something like this?

function myFunction(): void {
    // This function modifies the input
    // ...
    this.displayAlert = true;
}

ionViewCanLeave() {
    if(this.displayAlert) {
        let alertBox = this.alertCtrl.create({
            title: 'Exit',
            message: 'Are you sure you want to leave?',
            buttons: [{
                    text: 'Exit',
                    handler: () => {
                        alertBox.dismiss().then(() => {
                            this.leavePage();
                        });         
                    }
                },
                {
                    text: 'Stay',
                    handler: () => {
                        // Do something in case the user decides to stay?
                    }
                }]
        });

        // Display the alert box
        alertBox.present();

        // Return false to prevent the page from being popped up
        return false;
    }

    return true;
}

private leavePage() {
    this.displayAlert = false;
    this.navCtrl.pop();
}

If the page was set as root, you can replace this.navCtrl.pop(); with

this.navCtrl.setRoot(anotherPage);

Answer №2

According to the official documentation, you can implement it in the following way:

ionViewCanEnter(): boolean{
   // This is where we decide whether to allow entry into this view
   // Return true if randomValue is valid, false otherwise
   if(isValid(randomValue)){
      return true;
    } else {
      return false;
    }
  }

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

The type 'Promise<void>' is lacking the properties that are required by the type

I am having difficulty understanding the error message that says: The type 'Promise<void>' is missing the following properties from type 'InventoryModel[]': length, pop, push, concat, and 28 more. TS2740 Below is my functional co ...

Experiencing CORS problem on Angular asp.net core application running on a local Mac OS machine

An error occurred while trying to call the API from the Annular App: "Origin https://localhost:44419 is not allowed by Access-Control-Allow-Origin." Inquiry Why am I encountering cross-origin restrictions when both the ASP.NET app and Angular server are ...

Is there a way to access the badge hidden behind the collapsible menu in bootstrap 4?

After moving from bootstrap 3 to bootstrap 4, my items no longer align properly. I've scoured the entire Internet for a solution, but I've run out of options (and patience.. haha) This is how it currently looks: https://i.sstatic.net/ra22j.png ...

Adjusting the alignment of button text in an Angular Kendo grid

I am currently utilizing the grid view feature of Kendo UI for Angular. While I have buttons on the grid, the issue is that the text within the buttons is not centered properly despite applying styles such as text-align:center. Here is the template for my ...

Can optional parameters be used to restrict TypeScript overloads in any way?

My objective is as follows: interface ColorRgb { red: number; green: number; blue: number; } function rgbToHex(red: ColorRgb, green?: undefined, blue?: undefined): string function rgbToHex(red: number, green: number, blue: number): string function r ...

Continuously apply the template in a recursive manner in Angular 2 without reintroducing any duplicated components

Recently, I delved into the world of angular 2 and found it to be quite fascinating. However, I'm currently facing a roadblock and could really use some assistance. The scenario is as follows: I am working on creating a select box with checkboxes in ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

Using the useStaticQuery hook outside of a function component is not allowed and will result in an invalid hook call error. Remember to only call

I am currently facing an issue while trying to retrieve values using useStaticQuery from my gatsby-config.js file. Below are snippets of my code. Does anyone have any suggestions on how to resolve this problem? Thank you in advance. Repository: https: ...

Is it possible to globally modify the component reference <dropdown-component> name in Angular during runtime in a dynamic manner?

I am currently working on an application that utilizes a component called "dropdown-component" throughout its pages. However, due to specific business requirements, I have been tasked with replacing "dropdown-component" with "custom-dropdown-component". Un ...

steps for setting up firestore database

Hey there, I'm trying to retrieve data from Firestore within a cloud function. To initialize Firebase, I have a file called firebase.ts: import * as admin from "firebase-admin"; import { getFirestore } from "firebase-admin/firestore&quo ...

An unexpected 'foo' key was discovered in the current state being processed by the reducer when using redux-toolkit's configure store and a customized store enhancer

I've been working on developing a custom store enhancer to add new values to my root state. However, I've encountered an unexpected key error after delving into the complexities of custom enhancers. While I can see the new state part in devtools ...

Checking the next route in Angular 2 when navigating away

Is there a way to trigger an action only on specific NavigationEnd router events, excluding when navigating between child routes or on a particular route? This is a snippet from my app.routing.ts: // other route configurations... { path: 'scrapers/ ...

I am encountering an issue with Angular where the following error message is displayed: "src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'"

This code snippet is from my app.component.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...

Incorporating an array of objects into another array of objects in Angular2 and Typescript, focusing on specific object fields

While I have experience operating on arrays of objects, the need to push one array into another has never arisen for me. Currently, my object format looks like this: data: [{ "name": "Btech", "courseid": "1", "courserating": 5, ...

IntelliJ IDEA mistakenly believes that the MouseEvent interface has already been declared

Can someone help explain the error TS2687:All declarations of 'x' must have identical modifiers.? I'm diving into the documentation for TypeScript to grasp the language better. The code snippet from the Function Parameter Bivariance section ...

Ionic 5 navigation problem: No routes were found

Recently started a new project with Ionic 5. I'm attempting to add pages to the "tabs" folder to keep the tab bar at the bottom. Using the CLI, I successfully added two pages and their routes to app-routing.module.ts, which worked without any issues. ...

The functionality of Flowbite Drawer is disabled when used within an ngFor loop in Angular

Currently, I am utilizing Flowbite () as a Tailwind CSS plugin in my Angular project. Everything is functioning perfectly except for an issue that arises when I try to call a drawer button within a table generated using ngFor. Unfortunately, I am at a los ...

Creating two separate Angular modules locally can be accomplished by first developing Module B and ensuring it is imported in

When working on two local projects in AngularJS where one imports the other, I found a simple solution. I would run "npm link" in module B's folder and then run "npm link module-B" in my main module's folder. Any changes made to a file in module ...

Angular Fails to Identify Chart.js Plugin as an Options Attribute

Encountering issues with using the 'dragData' plugin in Chart.js 2.9.3 within an Angular environment: https://github.com/chrispahm/chartjs-plugin-dragdata After importing the plugin: chartjs-plugin-dragdata, I added dragdata to the options as sh ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...