Angular Route Reuse Strategy

JS
S
JavaScript

Angular reuses components when it can but destroys them to free memory otherwise and this is the desired behavior in most cases.

1import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router';
2
3export class TodayRouteReuseStrategy implements RouteReuseStrategy {
4  private storedRoutes = new Map<string, DetachedRouteHandle>();
5
6  // Leaving Route
7  shouldDetach(route: ActivatedRouteSnapshot): boolean {
8    return route.data.key === 'today';
9  }
10  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
11    this.storedRoutes.set(route.data.key, handle);
12  }
13
14  // Entering Route (only if there is routeConfig and storedRoute)
15  shouldAttach(route: ActivatedRouteSnapshot): boolean {
16    return !!route.routeConfig && !!this.storedRoutes.get(route.data.key);
17  }
18  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
19    return this.storedRoutes.get(route.data.key);
20  }
21  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
22    return future.routeConfig === curr.routeConfig;
23  }
24}
25

Created on 7/1/2021