angularangular-ui-router

How to activate RouteReuseStrategy only for specific routes


Is there a way to implement RouteReuseStrategy only for specific routes?

Meaning each route with children, getting its own custom implementation of RouteReuseStrategy, and whose methods only fire when a route in a specific 'tree' is activated.

I currently use the code from this answer, but I want to expand it with the above logic if possible.


Solution

  • Create a custom route reuse strategy

    import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from "@angular/router";
    
    export class CustomRouteReuseStrategy implements RouteReuseStrategy {
    
      handlers: { [key: string]: DetachedRouteHandle } = {};
    
      shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return route.data.shouldReuse || false;
      }
    
      store(route: ActivatedRouteSnapshot, handle: {}): void {
        if (route.data.shouldReuse) {
          this.handlers[route.routeConfig.path] = handle;
        }
      }
    
      shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
      }
    
      retrieve(route: ActivatedRouteSnapshot): {} {
        if (!route.routeConfig) return null;
        return this.handlers[route.routeConfig.path];
      }
    
      shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.data.shouldReuse || false;
      }
    
    }
    

    In your router module, implement the new strategy in the providers array:

    providers: [
      { provide: RouteReuseStrategy, useClass: CustomRouteReuseStategy },
      ...
    ]
    

    Then, declare the desired route with a data property 'shouldReuse' set to true

    { path: 'myPath', component: MyComponent, data: { shouldReuse: true } },
    

    Only the routes with the data property shouldReuse set to true will be reused.