Is there a way to interrupt the routerLink function when a user is prompted in Angular 4+?

I am seeking to replicate the traditional functionality found in HTML where clicking a link triggers a confirmation pop-up before being redirected:

<a href='http://www.example.com' onclick="if ( window.confirm ('Are you sure you want to go there?') === false ) { return false; } ">goto example.com</a>

If the user clicks cancel, the browser remains on the current page. Simple and effective.

But how can this be achieved using Angular-based HTML? It seems the typical approach doesn't quite work:

<a routerLink='/go-there'> go </a>

As we've seen, adding an onclick event like above does not produce the desired result.

<a routerLink='/go-there' onclick="if ( window.confirm ('Are you sure you want to go there?') === false ) { return false; } "> go </a>

Currently, I'm handling this in the .ts file while still utilizing routerLink, as shown below:

const user_approval = window.confirm ('Are you sure you want to go there?');
if ( !user_approval ) {
  alert('Action is cancelled. \nYou are not going there.');
  return false;
}

This method works but only after the routerLink has already been activated, which could have been avoided.

So, how can we prevent the routerLink destination from being accessed if the user changes their mind about proceeding?

Answer №1

It's recommended to approach this task differently. To begin, delete routerLink from your HTML and utilize (click) instead of onclick :

<a (click)="check()">GO</a>

In your component, incorporate the Angular router module:

import { Router } from '@angular/router';

constructor(private router: Router) {}

  check() {
    const user_approval = window.confirm ('Are you sure you want to go there?');
      if ( !user_approval ) {
          alert('Action is cancelled. \nYou are not going there.');
          return false;
      } else {
          this.router.navigate(['/go-there']);
      }
  }

This method ensures that the function is executed based on the user's decision to navigate or not.

Answer №2

If you're looking for an alternative to using the click method + this.router.navigate, consider implementing a CanDeactivate Guard on the specific route where you want to include a prompt. (https://angular.io/api/router/CanDeactivate)

@Injectable()
export class CanDeactivateGuard implements CanDeactivate {

    constructor(){}

    canDeactivate(): boolean {
        let confirm = window.confirm('Are you sure you want to go there?');
        return confirm;
    }
}

This code snippet serves as a basic example of how to create a canDeactivate guard. For a live demonstration, check out this plnkr: (https://plnkr.co/edit/CW9ofxscCgaZMlWVrfer?p=preview)


Keep in mind that as you delve into more advanced prompt implementations, they are likely to be asynchronous. In such cases, it's recommended to encapsulate your implementation within an observable.

canDeactivate(): Observable<boolean> {
    return new Observable(observer => {
        // Example of an asynchronous prompt implementation
        bringUpSomePrompt('Are you sure you want to go there?', (confirm) => {
            observer.next(confirm);
            observer.complete();
        });
    });
}

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

Issue with index creation using the @index decorator in Typegoose with NestJS and MongoDB

Encountering an issue with typegoose. Trying to create a 2dsphere index on the property geoLocation of model SP. Utilized the typegoose decorator @index but it's not functioning and not throwing any errors. Uncertain about how typegoose handles this s ...

Is there a way to position the Image component from next/image using absolute positioning?

Is it possible to use an element Image from 'next/image' with the CSS style { position: absolute; left: 50% }? It appears that it is not being applied. For example: import React from 'react' import Image from 'next/image' imp ...

What sets the do/tap operator apart from other observable operators?

Can anyone clarify the distinction in simple terms between the typical observable operators used for observing output and why do/tap appear to serve the same purpose? What is the reason for utilizing do/tap? ...

Having trouble with combining two formgroups using concat in an Angular application

I have developed an angular form using reactive forms, with controls displayed on the left and right side. The controls on the right are labeled as "alternate" and are shown based on the selection of a radio button. To accommodate this, I have created two ...

Jodit-React: Addressing the Placeholder Problem

I've recently incorporated Jodit-react into my react-typescript project, but I encountered an error when adding the config property. The error message stated that it "Has no property common with type." Unfortunately, I'm unsure why this is happe ...

Both radio buttons are being chosen simultaneously

<div class="container"> <div class="row"> <form> <div class="form-group"> <label>username</label> <br /> <input type="text" class=" ...

Oops! The type '{}' is lacking the properties listed below

interface Human { firstName: string; lastName: string; } let human1: Human = {}; human1.firstName = "John" human1.lastName = "Doe" Upon declaring human1, an error pops up: Type '{}' is missing the following properties from type Human ...

Using React to display an HTTP response containing text or HTML content

I am currently developing an application that allows users to upload an .xls file to a server, and in return, they receive a text/html response. I am looking for a way to preview this response in a similar manner to what is seen in developer tools. Here is ...

Tips for effectively utilizing the Ngrx navigation function

While exploring NgRx, I stumbled upon navigation. According to the documentation, it seems like this effect should trigger when the component loads. However, I'm facing an issue where this effect is not getting triggered. Other effects that I've ...

The issue arises when attempting to apply CSS styles to an existing component or body tag,

I am currently working on an Angular 7 project where I have a requirement to dynamically load a component using routes. However, when I try to add styles for the body tag and existing component tags in the dynamically loaded component style-sheet, they do ...

Enhance your UI experience with a beautifully styled button using Material-

I was using a Material UI button with a purple background. <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', heig ...

Deploying Angular application on IIS results in errors specific to the IIS environment

I developed an application using .net 3.0 and Angular 8 in Visual Studio. I then updated Angular to version 10. While everything runs smoothly when I test the app locally, I encountered an error after publishing it on IIS: no such file or directory, open ...

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...

ngFor is failing to show the array data, which is being fetched from Firebase

Hi there, I understand that this question has been asked frequently, but the regular solutions are not working for me. ts handleChangeFormType(formType) { this.serverData.getData('questionnaire/' + formType) .subscribe( (response: Respons ...

Deducting days, hours, and more from the current time using Angular 2

I am attempting to calculate the difference in days, hours, and minutes from the current time. Following the instructions on npmjs website, I have successfully installed the necessary package using the command: npm install --save add-subtract-date. Next, ...

Having trouble with validation messages not displaying correctly in Angular after removing a value. What is the correct approach to fix this issue

I've encountered an issue with Angular validation where it's triggering validation on page load, which is not desired. Additionally, when I enter a value, the validation message disappears, but if I return to the textbox and delete the input, the ...

Is there a way to programmatically add a timestamp to a form in Angular6?

Is there a way to automatically populate new forms with the current datetime value? this.editForm.patchValue({ id: chatRoom.id, creationDate: chatRoom.creationDate != null ? chatRoom.creationDate.format(DATE_TIME_FORMAT) : null, roo ...

Assess the equation twice using angular measurement

I am attempting to assess an expression that is originating from one component and being passed into another component. Here is the code snippet: Parent.component.ts parentData: any= { name: 'xyz', url: '/test?testid={{element["Te ...

What is the process for integrating unit tests from external sources into an Angular project following an upgrade to version 15

As of Angular v15, the require.context function has been removed from the test.ts configuration file. I used to rely on require.context to expose tests outside of the Angular project to Karma. Now that it's no longer available: const contextGlobal = ...

Angular Material conflicting dependencies

Hello, I am embarking on my journey to learn Angular with Electron. Recently, I forked a repository at the following link: https://github.com/maximegris/angular-electron However, I have encountered a challenging dependency issue: ✘ daniel@daniel-HP-ZBoo ...