Angular Deprecates Event before Unload Event

My goal is to prevent the user from navigating to any link if there are unsaved changes, and it works correctly in most cases but there are two exceptions:

  1. When the user clicks on "Log Out"
  2. When the user clicks on a toggle button at the layout level

I attempted to restrict these actions using Events, however, it seems to be deprecated.

`

@HostListener('window:beforeunload', ['$event'])

  canDeactivate(): Observable<boolean> | boolean {

    if(*some condition*)
    {
      if(event)
      {
        event.preventDefault();
        event.stopPropagation();
      }
    }
      return *some condition*;

  }

`

All I want is to halt the request propagation

Answer №1

When utilizing an event, it is important to avoid using the outdated window.event variable.

To learn more about this deprecated method, you can refer to its documentation here

If you are encountering issues where you need to access the event passed as an argument to the canDeactivate method, keep in mind that this method does not actually have any parameters specified (even if you have declared one in your HostListener).

In order to resolve this, simply include the event within the method's parameters:

 canDeactivate(event: BeforeUnloadEvent): Observable<boolean> | boolean {

This ensures that you are utilizing the event from the method parameter rather than relying on the window object.

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

Unable to retrieve user attributes (provided as res.locals.user) in express and hbs view

Here is a snippet of code I use to verify user tokens and store the user information in req.locals: exports.isLoggedIn = async (req, res, next) => { if (req.cookies.jwt) { try { const decoded = await promisify(jwt.verify)( ...

Discover the technique for splitting a string using jQuery with multiple strings as separators

I am looking to split a string in jQuery or JavaScript using multiple separators. When we have one string as a separator, our code looks like this: var x = "Name: John Doe\nAge: 30\nBirth Date: 12/12/1981"; var pieces = x.split("\n"), p ...

How to apply color to text in Node.js

I am in the process of creating a web-based compiler using NodeJS. My main objective is to highlight syntax in different colors. For example, consider the following C code: int var; printf("%d",var); In this code snippet, I would like the "int" and "prin ...

Enhance Angular Form Functionality: Implement Button-Triggered Option Selection

My current Angular page features a select dropdown that is automatically populated with existing client addresses, including the option "Add New Address". Clicking on this option opens a modal window where a new address can be entered. Once the new address ...

Ways to activate the enter key

Here we have the input bar and search button setup in our HTML code: <div> <div class="input-group search-bar"> <input type="text" class="form-control search-box" placeholder="Search people" autofocus="" ng-model="searchPeople"& ...

Angular2 does not load Js twice

I specified the path to my JS file in angular.cli. It loaded successfully during the initialization of the Angular app, but when navigating back to the component, it failed to load. Any suggestions on how to fix this issue would be greatly appreciated. Th ...

Here is a unique rewrite: "Utilize jQuery to extract all data-id and amount from an HTML page, then send it through an

Is there a way to retrieve the data-id and amount values from this HTML page using jQuery? Once I have gathered that information, I would like to store it in an array and then submit it via an AJAX call. It's important to note that this is a Laravel p ...

Updating Sencha list itemTpl on the fly

Is there a way to dynamically change the itemTpl in a Sencha list to adjust the visibility of a column based on certain conditions? Your assistance would be greatly appreciated. ...

ways to disrupt a timeout

I am attempting to incorporate a functionality similar to this example: https://www.w3schools.com/jsref/met_win_cleartimeout.asp On my personal website: If you enter certain characters in the input field, select one of them, and then pause for 5 seconds, ...

Global variable-driven dynamic routing

I have multiple projects set up in a single Angular workspace and I need to dynamically change the routing based on a global variable defined in app.routing.ts. Here is a snippet from my app routing module: import { NgModule } from '@angular/core&ap ...

Retrieving updated data from a service does not trigger a refresh of the view

Having an issue with rendering data obtained from a service. Here is the situation: The service retrieves values from a distant API using an Observable: @Injectable() export class myService { constructor(private http: Http) { } getData(listLength: num ...

Angular SignalR template for ASP.NET Core 6

Is there a specific .NET template for an operational ASP.NET Core 6 application with SignalR and an Angular ClientApp using WebSockets transport? I've managed to only make the ServerSideEvents transport function. The 'dotnet new angular' co ...

accessing information from webpage using hyperlink reference

This seems to be a rather straightforward issue, but unfortunately, I lack the necessary expertise to address it. Despite conducting thorough research, I have been unable to find a solution - mainly because I am uncertain about what specific terms or techn ...

What is the best way to increase a numerical input?

While experimenting with HTML input elements, I decided to utilize the step attribute. This allowed me to increment the current value by 100 when clicking the up or down arrows in the input field. However, I discovered that the step attribute restricts th ...

Encountering an Unexpected Token Error While Parsing JSON with jQuery

Utilizing the Envato API with jQuery to collect user stats is my current project. An example JSON response that I will display is as follows: { "new-files-from-user":[ { "thumbnail":"http://3.s3.envato.com/files/60560.jpg", "tags":"", "use ...

Discover a non-null string within a deeply nested data structure

Within the 'task' object, the value of the 'door' property can vary each time it is accessed: var task = {}; task["123"] = [{"door":""}, {"door":""}, {"door":""}, {"door":""}]; task["456"] = [{"door":""}, {"door":"close"}, {"door":"" ...

Zebra Calendar Alignment Problem

Currently working on an asp.net app and utilizing the Jquery Zebra DatePicker. Encountering an issue where when opening the form in a Jquery dialog, the calendar appears at the bottom of the page instead of within the dialog. A similar problem was discus ...

Difficulty Establishing a Connection with SQL Server Using TypeORM

My local machine is running an SQL Server instance, but I'm encountering an error when trying to connect a database from TypeORM. The error message reads: originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (seque ...

Changing Marker Color in Google Maps API

There are multiple Google Maps Markers colors based on certain conditions being TRUE or not. In addition, these Markers will change color when the mouse hovers over a division (a1,a2..ax). I want the Markers to revert back to their original color when th ...

AngularJS: Modifying the template in a Directive with scoped attribute dependencies

As I delve into customizing a template within a directive and incorporating references to attributes in the parent scope, I find myself navigating through the Angular framework as a newcomer. My journey has led me to leaning on Customizing the template wit ...