Search code examples
angulartypescriptangular2-routingcandeactivate

How to trigger can-deactivate-guard when queryParams change?


I am using the following routing inside app-routing module:

path: "overview",
component: OverviewComponent,
children: [
    { path: 'edit', component: DetailComponent, canDeactivate: [CanDeactivateGuardService] }
]

My problem is that canDeactivate only triggers once, going from /overview to /overview/edit. I understand that part, because of the child's path inside the routing.

My question is what is a proper solution to make canDeactivate trigger whenever the queryParams change inside the edit path? For example, changing the url from /edit?id=1 to /edit?id=2 should trigger canDeactivate aswell.

Is there a simple solution that can be implemented from inside the routing module?
If not, what do you propose?
Keep in mind that I am still learning angular.


Solution

  • You can define when guards and resolvers will be run by setting RunGuardsAndResolvers property on router config.

    path: "overview",
    component: OverviewComponent,
    children: [
        { path: 'edit',  runGuardsAndResolvers: 'pathParamsOrQueryParamsChange', component: DetailComponent, canDeactivate: [CanDeactivateGuardService] }
    ]