Skip to content

Instantly share code, notes, and snippets.

@mattuu
Last active September 2, 2019 09:13
Show Gist options
  • Save mattuu/42bd38cdbc789b06437f7cc23c13ce53 to your computer and use it in GitHub Desktop.
Save mattuu/42bd38cdbc789b06437f7cc23c13ce53 to your computer and use it in GitHub Desktop.
Angular 5 compatible unsaved changes guard, displaying warning to user if changes been made do form and user tried to navigate away from the screen without saving data.
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import { EditableDataComponent } from './editable-data.component';
@Injectable()
export class UnsavedChangesGuard implements CanDeactivate<EditableDataComponent> {
canDeactivate(component: EditableDataComponent): Observable<boolean> | boolean {
if (!component || !component.hasUnsavedChanges) {
return true;
}
if (component.hasUnsavedChanges()) {
const promise = new Promise<boolean>((resolve, reject) => {
const answer = confirm('You have unsaved changes. \nSelect OK to ignore changes or cancel to stay on this page.');
resolve(answer);
});
return Observable.from(promise);
} else {
return true;
}
}
}
export const UNSAVED_CHANGES_GUARD_PROVIDER = [UnsavedChangesGuard];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment