📎 Webclip
Angular LAB: Preserving Component State Across Route Transitions
The article explains that navigating away from a route can make Angular fetch data again and also discard DOM state, which is especially troublesome for forms and other UI elements. It proposes a custom RouteReuseStrategy to keep components cached when leaving a route and restore them later, while using route data flags to control reuse and avoid sharing state between parameterized routes.
Reading notes#
- Shows two problems when switching routes: refetching requests and losing DOM state.
- Proposes
RouteReuseStrategyto store components instead of destroying them when leaving the route. - Uses
storeRoute: truefor routes that should be preserved andnoReuse: trueto prevent reuse in routes with parameters. - Creates helpers to build the full route path and compare objects such as
paramsandqueryParams. - Implements a route cache with
DetachedRouteHandleand methodsshouldDetach,store,shouldAttach,retrieveandshouldReuseRoute. - Includes methods to clear a route or clear everything, because components in cache do not go through
ngOnInitagain and can cause memory leaks. - The result keeps state when returning to the route and allows manual use of the cache when needed.
