let’s make something together

Give us a call or drop by anytime, we endeavour to answer all enquiries within 24 hours on business days.

Find us

PO Box 16122 Collins Street West
Victoria 8007 Australia

Email us

info@domain.com
example@domain.com

Phone support

Phone: + (066) 0760 0260
+ (057) 0760 0560

Creating Reusable Angular Components – Angular Reuse Strategy

  • By Preetha Ravi
  • February 18, 2020
  • 1394 Views

Routing is navigating a web page to one to another in a web application. Angular is a Javascript framework that has a built-in router. This default function is primarily used to navigate to other pages from the home page. You can easily create custom routes with fewer efforts using this approach.
By importing the routing module into the app module, you can initialize the routes. We can even pass the parameters or query parameters through the routes. Though we use different parameters and query parameters, Sometimes we can’t navigate the page to the same page from which we are in. To overcome this problem, we are using the concept called reuse strategy in Angular.
Let’s see how can resolve the problem in routing

Reuse Strategy In Angular

The first step of using the reuse strategy in angular is that we want to extend the reuse strategy abstract class of the Router. For that, we need to write a custom reuse strategy class and we should import it on the app module and finally, we should provide the function in the provider of an app module.
Now you can import the “RouteReuseStrategy” class from the angular/router library and to import the class in the app module follow the below code,

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

Also Read: Building Dynamic Nested Reactive form In Angular

Next, we are going to see the abstract classes in “RouteReuseStrategy” class from the router.

export abstract class RouteReuseStrategy {
/** Determines if this route (and its subtree) should be detached to be reused later */
abstract shouldDetach(route: ActivatedRouteSnapshot): boolean;
/** Stores the detached route */
abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void;
/** Determines if this route (and its subtree) should be reattached */
abstract shouldAttach(route: ActivatedRouteSnapshot): boolean;
/** Retrieves the previously stored route */
abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle;
/** Determines if a route should be reused */
abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
}

Above abstract class contains 5 methods,

shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot),
abstract shouldDetach(route: ActivatedRouteSnapshot),
abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void
abstract shouldAttach(route: ActivatedRouteSnapshot): boolean;
abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle;

shouldReuse() method is used to tell whether we want to reuse the route or not. If it returns true then it will reach the shouldDetach() method and shouldAttach() method.
If shouldDetach() returns true then it will get into the store method where you can store the data that is coming from routes, on other cases, if shouldAttach() method returns true then it will reach to Retrieve where you can retrieve the stored data from routes and it will end the process. If both returns are false then it will directly quit the process.

All these codes should be extended in the class named as customresuestrategy class. You can see the below sample I have given below,

import {
ActivatedRouteSnapshot, RouteReuseStrategy,
DetachedRouteHandle
} from '@angular/router';
export class CustomReuseStrategy implements RouteReuseStrategy {
// Specify the routes to reuse/cache in an array.
routesToCache: string[] = ["dashboard", "spd/customer"];
storedRouteHandles = new Map<string, DetachedRouteHandle>();
// Decides if the route should be stored
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return this.routesToCache.indexOf(this.getPath(route)) > -1;
}
//Store the information for the route we're destructing
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
this.storedRouteHandles.set(this.getPath(route), handle);
}
//Return true if we have a stored route object for the next route
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return this.storedRouteHandles.has(this.getPath(route));
}
//If we returned true in shouldAttach(), now return the actual route data for restoration
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
return this.storedRouteHandles.get(this.getPath(route)) as DetachedRouteHandle;
}
//Reuse the route if we're going to and from the same route
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
if(future.component && (<any>future.component).name == "ShowComponent" ){
return false;
}
return future.routeConfig === curr.routeConfig;
}
// Helper method to return a path,
// since javascript map object returns an object or undefined.
private getPath(route: ActivatedRouteSnapshot): string {
let path = "";
if (route.routeConfig != null && route.routeConfig.path != null)
path = route.routeConfig.path;
return path;
}
}

The getpath method is used to get the path of the route. The detached handle will have the stored information in the handle which is to be retrieved.

Related: How To Create Observables In Angular

I have done a reuse strategy for a single component. In the same way, you can also use this reuse strategy for multiple components. So write your custom logic to reuse the particular component wherever you need with the help of this quick tutorial.
Hope you find the content useful! Give it try and let us know how was your experience. Have any queries? Drop it in the comment section below.
Don’t forget to subscribe to the weekly newsletter if you need regular updates on Angular development.
If you are looking for angular developers? Hire Angular developer from Agira Technologies to build the best web-apps at affordable rates. Our dedicated Angular developers are well-versed with all the updates and ensure top-notch web application development to meet your business requirements. Talk with our experts today!

Turn your vision to magnificent reality With
Our Web and Mobile Solutions