Last active
September 2, 2019 09:13
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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