Having an issue with the CanDeActivate()
function in Angular2
. The problem arises when a user tries to leave a page while in edit mode, triggering a popup with Yes, No, and Cancel options.
If the user clicks on Cancel, the popup closes. If they click on No, the popup closes and redirects them to another page upon further navigation.
Imagine an application with modules A, B, and C. Module C contains the edit screen. If a user makes changes on that page and without saving, tries to navigate to Module B, a popup appears with Yes, No, and Cancel buttons. Choosing cancel keeps the user on the same page, but if they attempt to go back to Module B, nothing happens. If they try to navigate to Module A, the popup reappears.
Currently stuck on this issue and would appreciate any help available. Thank you in advance for any assistance provided.
MyComponent.ts
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean = () => {
if (this.isEdited) {
this.showConfirmationModal = true;
this.canLeavePage.asObservable().first();
return false;
}
return true;
}
Can-Deactivate.guard.ts
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate) {
let can = component.canDeactivate();
if (!can) {
return false;
}
return true;
}
}