Skip to content

Instantly share code, notes, and snippets.

@Splaktar
Last active March 13, 2023 18:23
Show Gist options
  • Save Splaktar/dcf2f7e98b4cf3f7b87c1c4ff3e6b2b5 to your computer and use it in GitHub Desktop.
Save Splaktar/dcf2f7e98b4cf3f7b87c1c4ff3e6b2b5 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();
}
});
});
}
}
@jayaprakashinstrive
Copy link

thank you so much it works super...

@samhDV
Copy link

samhDV commented Mar 8, 2022

I think this will only work when the canDeactivate method returns a boolean. When it returns a promise or observable, the check in line 18 (component.canDeactivate()) will always be truthy and thus always result in the return true.

@Splaktar
Copy link
Author

Splaktar commented Mar 8, 2022

@samhDV yeah seems to be correct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment