Angular's HostListener triggers twice when the browser's back button is clicked

In my Angular application, I have implemented a @HostListener that triggers when the back button on the browser is clicked. However, I have noticed that the event handler seems to be firing twice - prompting two dialogue boxes when clicking 'Ok'. This leads me to believe that there may be a bug causing this behavior.

@HostListener('window:popstate', ['$event'])
  onBrowserBackBtnClose(event: Event) {
    // If we can go back...
    if (this.canGoBack) {
      alert('Are you sure you want to go back and exit the review?');
    }
  }

I am wondering if this issue is specific to Angular or if it is a normal behavior related to routing mechanisms. Additionally, I would like to know if there is a way to fix this problem or implement a workaround. Perhaps there is a more effective way in Angular to handle actions triggered by the back button click?

Answer №1

The HostListner is simply reporting the events, so it's possible that the page is being pushed or stacked multiple times. Without seeing the rest of your code, I would guess it's either

  1. due to navigation
  2. done programmatically
  3. related to the router/outlet

Check out this link where someone else encountered a similar issue. Take a look at the stack and the nav menu/router control. This solution should guide you in resolving the problem!

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

What steps can I take to eliminate the overload error that occurs when I extend the Request object in Express?

I'm having trouble extending Express' Request object to access req.user, and I'm encountering an overload error. I've attempted a couple of solutions, but none of them seem to work for me. EDIT: I am currently using Passport.js and JWT ...

Why is passing data:{} to a route essential for achieving the desired outcome?

Check out the Angular Material Documentation Site passing {} to the Homepage route: {path: '', component: HomePage, pathMatch: 'full', data: {}} I'm interested in knowing the significance of data: {}. Recent Discovery Closer ex ...

Generics in Typescript implemented for a React component that accepts an array of records along with an array of

I am currently working on developing a straightforward typed react component designed to display a table from an array of objects. The input data is structured as follows: // array of records containing data to render in the table data = [ { one: 1, ...

Launching Angular 4 front-end and .Net Web Api back-end simultaneously on the same IIS website results in a 404 error when refreshing the page

My web application consists of an Angular 4 front-end client-side code that communicates with a back-end services part written in ASP.NET WebAPI. I have deployed the application on IIS v10, within the same website. However, whenever I try to refresh the pa ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

Ways to conditionally display a component in Next.js without the issue of caching CSS styles

I'm a newcomer to Next.js and I'm still trying to wrap my head around how the caching works. Let's take a look at this simplified example: An index page that displays either Test1 or Test2 components, based on whether the current minute is ...

Encountering difficulty invoking a component method from d3's call() function

My current setup involves using D3 to drag and drop links in the following manner: .call(d3.drag() .on("start", linkDragStart) .on("drag", linkDragging) .on("end", linkDragEnd)); Recently, I decided to extract this functionality into a separate met ...

Discover how to set up lazy loaded child routes within a parent route that is also loaded lazily in Angular 2

Struggling to implement lazy loading for my app has been a series of challenges. I successfully implemented lazy loading for the main route, /admin, but now I am facing issues while adding another route, /admin/login. This is what I tried: admin-router.m ...

Narrow down your search results with date range filtering in Angular Material

Seeking guidance as a newcomer to Angular Material, I am trying to implement a date range filter for a table of N results. The options in the filter select are (1 day, 5 days, 1 week, 15 days), which are populated using a variable JS vm.rangos=[ {id ...

How to send a dynamic URL parameter to a function in Next.js TypeScript without using implicit typing

When utilizing the useRouter function with a parameter of type string, the following error is encountered: Type 'string | string[] | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type & ...

Make sure to utilize flatMap to call the second API every time

I am utilizing two APIs, API1 and API2. The output from API1 is used as an input for API2. In case the call to API1 fails, I still want API2 to be invoked with a blank value. this.Api1().pipe(flatMap(result => { return this.Api2(result); })).subscrib ...

Is there a way to alter the stroke color of an SVG icon in Angular 2 or 4 by clicking on it?

Having trouble with this code, can someone provide a solution? This is the SVG icon code: <svg id="Home" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52.28 43.49"> <defs> <style> .cls-1{fill:none;stro ...

Securing routes and layouts in the MEAN Stack framework

I am currently utilizing the MEAN Stack framework and have created 3 different layouts. I am looking to secure each layout route to prevent unauthorized access. const routes: Routes = [ { path: '', redirectTo: '/dashboard', ...

Error: Trying to access the 'blogpost' property of an undefined variable results in a TypeError while executing the NPM RUN BUILD command in Next.js

Encountering a frustrating issue while trying to run my Next.js application for production build. The problem seems to be related to the "blogpost" parameter in the following codeblock: import React from "react"; import Slab from "../../comp ...

Angular module cannot be located

While working on implementing a chat feature for my project using sockJS and STOMP, I encountered several challenges with installing these two libraries. Despite attempting various methods such as installation from index.html, npm install, and manual downl ...

An issue has occurred: Cannot access the properties of an undefined object (specifically 'controls')

I encountered an error message stating "TypeError: Cannot read property 'controls' of undefined" in the code that I am not familiar with. My goal is to identify the source of this error. Below is the HTML code snippet from my webpage: <div ...

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

Transform a JSON array into an array of objects using typescript

I have a JSON array that I need to convert into an object type array JSON array [ 0:{code: "00125", scheme: "0001", plotNumber: "125", propType: "001", plotType: "001"} 1:{code: "190", scheme: "0001", plotNumber: "NA 190", propType: "001", plotType: "0 ...

Having trouble utilizing datepipe with locale format

Currently, I'm constructing a website using angular2 final alongside webpack cli. One of my specific requirements is to showcase the date in the nl-NL locale. The html code snippet that I have written for this purpose looks like: {{eventDate | date:& ...

What is the best way to distinguish shared services from other services in Angular 6 and above?

There was a time when I frequently heard the term "shared services" in relation to sharing data between unrelated components in Angular. However, I started questioning whether every service is actually classified as a shared service or not. If it is cons ...