Search code examples
angularangular-routerangular-router-guards

Accessing component properties from CanDeactivate guard


I have multiple forms in an app and I have a CanDeactivate guard that prompts the user to confirm whether they want to leave the page without first saving the forms they have edited. Each component with forms has a hasBeenEdited function that checks if the form has been edited. Since I have only one CanDeactivate injectable class to handle all these components with forms, I need to access the hasBeenEdited function of the component where the user currently routed to. How best to accomplish this? I've seen examples where the canDeactivate function within the guard class is passed one component argument, but I'm not sure how to pass the currently routed component.


Solution

  • describe canDeactivate interface

    export interface CanDeactivateComponent {
      canDeactivate: () => Observable<boolean> | boolean;
    }
    

    describe guard

    @Injectable()
    export class CanDeactivateGuard implements CanDeactivate<CanDeactivateComponent> {
      canDeactivate(component: CanDeactivateComponent) {
        return component.canDeactivate ? component.canDeactivate() : true;
      }
    }
    

    describe route

     path: 'yourPath',     
     canDeactivate: [CanDeactivateGuard],
     component: YourComponent
    

    and component:

     ...
     class YourComponent implements CanDeactivateComponent {
     ...
       canDeactivate() { 
         ... everything you need to detect if you can leave route: return false, 
           or observable
       }