-
-
Save railsstudent/be8d391cea27fd10b64bad7a68f7da8b to your computer and use it in GitHub Desktop.
Guard against navigating away when there are unsaved changes
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 {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