Skip to content

Instantly share code, notes, and snippets.

@ntxinh
Forked from Splaktar/unsaved-changes-guard.ts
Created October 3, 2019 04:41
Show Gist options
  • Save ntxinh/63c99743a6f46e4d75ff559c101a5c4a to your computer and use it in GitHub Desktop.
Save ntxinh/63c99743a6f46e4d75ff559c101a5c4a to your computer and use it in GitHub Desktop.
Guard against navigating away when there are unsaved changes
import {CanDeactivate, Router} from '@angular/router';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class UnsavedChangesGuard implements CanDeactivate<CanComponentDeactivate> {
constructor(private dialog: MatDialog) {}
canDeactivate(component: CanComponentDeactivate) {
// Allow navigation if the component says that it is OK or it doesn't have a canDeactivate function
if (!component.canDeactivate || component.canDeactivate()) {
return true;
}
return Observable.create((observer: Observer<boolean>) => {
// UnsavedChangesDialog defined somewhere else and imported above
let dialogRef = this.dialog.open(UnsavedChangesDialog, {
data: {
message: 'You have unsaved changes. Are you sure you want to leave this page?'
}
});
dialogRef.afterClosed().subscribe(result => {
observer.next(result);
observer.complete();
}, (error) => {
observer.next(false);
observer.complete();
}
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment