I want to show a prompt on screen to the user if they are trying to navigate away from a page in which they have made changes to a form. I have created a Guard so far, and successfully got it to log something in the console when the user navigates away from this page. But now, I need to show a Dialog
box warning them, and they should be able to cancel the 'navigation' or confirm that they wish to navigate away.
I have a method in my component containing the form that checks whether or not changes have been made to the form, now I just need to implement the rest described above.
Here is my Guard:
import { Injectable } from '@angular/core';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RouterGuardGuard implements CanDeactivate<unknown> {
canDeactivate(
component: unknown,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
console.log('TESTING');
return true;
}
}
I have implemented the guard for my component inside my app-routing-module.ts
as such:
{ path: 'users/edit/:id', canDeactivate: [RouterGuardGuard], component: UserEditorComponent },
So, if the user makes changes to the form inside of the UserEditorComponent
I need to show a dialog box before the navigation occurs, I already have the component for this dialog box, which I use in different parts of my app.
Thanks