How to activate RouteReuseStrategy only for specific routes
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.