Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally Apply router reuse strategy for angular2 routes

Tags:

angular

I came to know about Sticky Routes to reattach the earlier component data when navigated back to the same component.I have implemented a demo by looking at this https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx blog here https://plnkr.co/edit/KVlRi9PtPeOpvn8bECBi?p=preview ... Is it Possible to have the apply conditions so that routerreusestrategy apply only for few components?

like image 661
abhilash reddy Avatar asked Jan 05 '17 10:01

abhilash reddy


People also ask

How do you implement route reuse strategy?

Custom Route Reuse StrategyshouldDetach : Determines if this route (and its subtree) should be detached to be reused later. store : Stores the detached route. shouldAttach : Determines if this route (and its subtree) should be reattached. retrieve : Retrieves the previously stored route.

What is Route reuse strategy?

BaseRouteReuseStrategylink This base route reuse strategy only reuses routes when the matched router configs are identical. This prevents components from being destroyed and recreated when just the fragment or query parameters change (that is, the existing component is reused).

What is Runguardsandresolvers?

RunGuardsAndResolverslink type-alias. A policy for when to run guards and resolvers on a route.

How do you use shouldReuseRoute?

shouldReuseRoute This method is called everytime we navigate between routes. The future is the route we are leaving (not sure why is called future) and curr is the route we are landing. If it returns TRUE the routing will not happen (which means that routing has not changed).


1 Answers

You need only minor modification of the original solution: https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx

Add shouldDetach flag to your route:

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent, data: { shouldDetach: true } },
  ...
];

And modify shouldDetach method in CustomReuseStrategy:

public shouldDetach(route: ActivatedRouteSnapshot): boolean {
  return route.data && (route.data as any).shouldDetach;
}

Here is your plunker updated: https://plnkr.co/edit/otbZBuRmGYQXeY6b4Sfp?p=preview

like image 128
Michal Moravcik Avatar answered Oct 21 '22 09:10

Michal Moravcik