Is it possible to track when a user switches to a different component in Angular?

I'm looking to set up a confirmation popup when the user attempts to navigate to a different page. I've come across information about hostListener and canActivate, but I'm not exactly sure how to begin! Any guidance would be greatly appreciated. Thanks in advance.

Answer №1

To start, you must create a guard for routing by creating a file named can-exit.guard.ts


import {Injectable} from '@angular/core';
import {CanDeactivate} from '@angular/router';

import {Observable} from 'rxjs';

export interface CanExit {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class CanExitGuard implements CanDeactivate<CanExit> {
  canDeactivate(component: CanExit) {
    if (component.canDeactivate) {
      return component.canDeactivate();
    }
    return true;
  }
}

Next, create another file named canExit.ts to handle returning the promised value.

import {Observable} from 'rxjs';

export interface CanExit {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

Once you have added these files to your application, configure the router file as shown below:

const routes: Routes = [
  {
    path: 'your Path name',
    component: YourComponent ,
    canDeactivate: [CanExitGuard],
  }
];
// Apply this configuration to every path in your application

Make sure to include canactivate in your component file by making some changes:


import { CanExit } from './../can-exit.guard';  //important


@Component({
  // include your selector and component definitions here
})
export class YourComponent implements OnInit, CanExit {

  constructor() { }

  ngOnInit() {
  }

  canDeactivate(): Promise<any> | boolean {
    const confirmResult = confirm('Are you sure you want to leave this page ? ');
    if (confirmResult === true) {
      return true;
    } else {
      return false;
    }
  }

}

I hope this information proves helpful.

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

Ensuring the correct type for an object's interface property value

I am currently working on defining a new interface interface SUser { ID: number; NAME: string; MAIL: string; PASSWORD: string; GENDER: number; BIRTHDATE: string; ID_FB: string; CREDIT: number; ID_REFERRAL: number; } My objective is to c ...

Page refreshing in Angular 5 consistently redirects to the home page instead of staying on the current page

I am experiencing an issue with the navigation on my application. When I navigate to routes like getEmp-by-id or page-not-found and hit refresh, the application automatically redirects me back to app-home. However, I would like it to stay on the same pag ...

Error in Typescript TS2322: Observable Type 'boolean | {}' - Using Angular 5 and Typescript 2.4.2

After upgrading from version 4 to 5, I'm puzzled by the plethora of TypeScript TS2322 errors I'm encountering. The migration involved setting up a new Angular project with the Angular CLI. Angular CLI: 1.5.5 Node: 8.9.1 OS: darwin x64 Angular: 5 ...

What is the best method to reset values in ngx-bootstrap date picker?

At the moment, it is only accepting the most recently selected values. To see a live demo, click here. ...

Using a custom TemplateRef in NgxDatatable

In the project I am currently working on, the tables have a specific wrapper around them. To prevent repetition of code, I am seeking a method to create a template where each component passes an ng-template that will be rendered within the custom table tem ...

What is the essential setup needed for a bootstrap dropdown list?

I'm currently working on an Angular project and I've been trying to implement the dropdown navbar from Bootstrap. I simply copied the code from here, but unfortunately, the dropdown feature isn't functioning properly for me: // I've att ...

React - retrieving the previous page's path after clicking the browser's "back" button

Imagine I'm on Page X(/path-x) and then navigate to page Y(/path-y). Later, when I click the "back" button in the browser. So my question is, how do I retrieve the value of /path-y in PageX.tsx? Note: I am utilizing react-router-dom ...

Derive a subset Union from a Union in Typescript

Here is a scenario with a Union type I'm working with; type MyUnionType = 'foo' | 'bar' | 'baz' What I need to do is create a new Union called MySubUnion, which will be a subset of the original; type MySubUnion = &apos ...

Issue encountered during ng2-redux installation

While attempting to use the https://www.npmjs.com/package/ng2-redux link, I encountered an issue when running npm install redux ng2-redux --save. Here is the stacktrace of the error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files& ...

Steps for fixing the error message "Type 'Observable<string>' is not assignable to type 'Observable<{ userId: string; partyId: string; }>'"

Having some trouble with my Angular project. I have this code snippet in my getUser() method, but the compiler isn't happy about it and I can't seem to figure out what's wrong: public getUser(): Observable<{ userId: string; partyId: strin ...

Dealing with routing problems within sub-routes using Angular 2 and Express, attempting to serve content from sub-folders

I am currently using Express to serve a local Angular2 application. To enable the Angular2 app to access various node_modules from Express, I have set up the following configuration: config.dependencies = [ { staticPath: './node_modules/@angular/&a ...

Definition file in TypeScript for an npm package provided by an external source - constructor

In my Node project, I am utilizing ES6 and Typescript. Despite this, there is a commonjs library that I need to incorporate. To address this, I have created my own .d.ts declaration file for the library: module "@alpacahq/alpaca-trade-api" { e ...

What method can be used to start an Angular app without the need for recompilation?

When I first created my Angular app, I used the command ng serve to build and run it. This command produced the following output: 10% building 3/3 modules 0 activei 「wds」: Project is running at http://localhost:4200/webpack-dev-server/ i 「wds」: we ...

Transforming a function into an array in TypeScript

I attempted to use the map() function on a dataURL array obtained from the usePersonList() hook, but I am struggling to convert my function to an array in order to avoid errors when clicking a button. import Axios from "axios"; import React, { us ...

Learn how to generate specific error messages based on the field that caused the failure of the @Column({ unique: true }) Decorator. Error code 23505

Hey there! I'm currently facing an issue while trying to handle Sign Up exceptions in my code. I want to inform the user if their username OR email is already in use. Although using the decorator @Column({ unique: true}) allows me to catch error 23505 ...

Is there a way to ensure that @angular/core is utilizing the most up-to-date version of zone.js in its peerDependencies configuration?

This code passes the test, but there is an issue: it('should successfully retrieve data when getDownloadProgress() is called', (done: DoneFn) => { let response = { 'process': {}, 'success': 'success ...

Issue: Unable to locate module: Error: The system is unable to find the src/app/app.component.css file?ngResource Angular

I am encountering three issues that I cannot seem to pinpoint the mistakes. Error: Module not found: Error: Unable to locate 'C:/Users/DexSh/desktop/C# Angular/Testing/src/app/app.component.css?ngResource' in 'C:\Users\DexSh\ ...

How do I set up middleware with async/await in NestJS?

I am currently integrating bull-arena into my NestJS application. export class AppModule { configure(consumer: MiddlewareConsumer) { const queues = this.createArenaQueues(); const arena = Arena({ queues }, { disableListen: true }); consumer. ...

Any ideas on how to fix the issue of 'type' property being absent in 'AsyncThunkAction' with Redux Toolkit while working with TypeScript?

While working with Redux Toolkit and the thunk/slice below, I decided to handle errors locally instead of setting them in state. To achieve this, I followed the example provided here. Although I could have set an error in the state, I wanted to explore wh ...

Steps for transitioning a VUE JS project to TypeScript

Is it possible to transition a VUE JS project from JavaScript to TypeScript without rewriting everything? I heard from a friend that it can be done through the VUE CLI, but I haven't been able to find any documentation or articles on this method. Has ...