A challenge I am facing is how to display a warning prompt on the screen if the user tries to leave a page after making changes to a form. I have successfully created a Guard that logs a message to the console when the user attempts to navigate away from the page. Now, my next step is to show a pop-up dialog box to warn them and give them the option to either cancel the navigation or proceed.
Within the component hosting the form, I have a method to detect any changes made to the form. What remains now is to implement the functionality described above.
Below is the code for 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 integrated the guard for my component in my app-routing-module.ts
like this:
{ path: 'users/edit/:id', canDeactivate: [RouterGuardGuard], component: UserEditorComponent },
Therefore, whenever changes are made to the form in the UserEditorComponent
, I need a dialog box to appear before the navigation takes place. I already have the dialog box component set up, which is used across various sections of my application.
Thank you