Angular 2/4 : how to change route without recreating the component

Issue

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 ?

Solution

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

Answered By – Poul Kruijt

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.