Last active
March 13, 2023 18:23
-
-
Save Splaktar/dcf2f7e98b4cf3f7b87c1c4ff3e6b2b5 to your computer and use it in GitHub Desktop.
Guard against navigating away when there are unsaved changes
This file contains 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
@samhDV yeah seems to be correct.