ranjith kotian
ranjith kotian

Reputation: 21

how to alert user on click of browser back button in angular 4?

how to alert the user on click of browser back button in angular 4?

onpopstate gets called even when the page loads for the first time

import {  PlatformLocation } from '@angular/common';

    constructor( private platformLocation: PlatformLocation) {
        platformLocation.onPopState(() => {
          console.log("onPopState called");
          window.alert("your data will be lost");
        })
    }

Upvotes: 2

Views: 6224

Answers (2)

Shrey Kejriwal
Shrey Kejriwal

Reputation: 736

Add a candeactivate guard

can-deactivate-guard.service.ts

import {Observable} from 'rxjs';
import {CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';

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

export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate, 
                currentRoute: ActivatedRouteSnapshot,
                currentState: RouterStateSnapshot,
                nextState?: RouterStateSnapshot
                ) : Observable<boolean> | Promise<boolean> | boolean {
    return component.canDeactivate();
  }
}

in your routing setting

const route: Route = [
  {path: '', component: AppComponent, canDeactivate: [CanDeactivateGuard]}
]

Provide your can Deactivate guards in your app.module in providers array.

Consider the following component where I have variable to check changes Saved

export class AppComponent implements CanComponentDeactivate {
   changesSaved = false;
   onUpdateServer() {
     this.changesSaved = true;
   }
   canDeactivate() {
      if(this.changesSaved) {
        return true;
      } else {
        return confirm('Do you want to discard changes');
      }
   }
}

Upvotes: 8

shubham agarwal
shubham agarwal

Reputation: 177

You can use ngOnDestroy inside the component.It will be called automatically when component is going to be destroyed and you can then alert any warning.

Upvotes: -1

Related Questions