warn user before leaving page angular

Solutions on MaxInterview for warn user before leaving page angular by the best coders in the world

showing results for - "warn user before leaving page angular"
Elouise
06 Nov 2017
1import { CanDeactivate } from '@angular/router';
2import { Injectable } from '@angular/core';
3import { Observable } from 'rxjs/Observable';
4
5export interface ComponentCanDeactivate {
6  canDeactivate: () => boolean | Observable<boolean>;
7}
8
9@Injectable()
10export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
11  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
12    // if there are no pending changes, just allow deactivation; else confirm first
13    return component.canDeactivate() ?
14      true :
15      // NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
16      // when navigating away from your angular app, the browser will show a generic warning message
17      // see http://stackoverflow.com/a/42207299/7307355
18      confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
19  }
20}
21