0

I have several routes to the same component (namely /projects, /projects/create, /projects/:id and children, all pointing to my ProjectComponent). When navigating between /projects/:id with only :id changing everything is fine, I can subscribe to the params and update my content accordingly, but when I navigate from /projects to /projects/create or to /projects/:id, the component is recreated.

Is there any way to navigate to a route pointing to the same component without it being recreated ?

JeanJacques
  • 1,754
  • 1
  • 12
  • 25
  • 1
    Possible duplicate of [How to redirect to an external URL from angular2 route without using component?](https://stackoverflow.com/questions/40150393/how-to-redirect-to-an-external-url-from-angular2-route-without-using-component) – k11k2 Aug 07 '17 at 13:41

1 Answers1

0

You should implement a custom RouteReuseStrategy

Create a service implementing the RouteReuseStrategy:

export class CustomReuseStrategy implements RouteReuseStrategy {

    handlers: {[key: string]: DetachedRouteHandle} = {};

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return true;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        this.handlers[route.routeConfig.path] = handle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        if (!route.routeConfig) return null;
        return this.handlers[route.routeConfig.path];
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
    }
}

And add this provider to the @NgModule:

providers: [
    {provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
]

You can adjust the CustomReuseStrategy to only have certain paths where the component can be reused, but I'll leave that up to you to find out how.

source

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • Thanks it's perfect, I actually came across this article but I dismissed it because the whole attach/detach/store/retrieve thing wasn't what I was looking for. I need to pay more attention. – Quentin Rouquette Aug 07 '17 at 20:48