Is there a way to name a route in Angular 7?

RafaelTSCS picture RafaelTSCS · Dec 4, 2018 · Viewed 8.4k times · Source

I was wondering if there is a way to name my routes in Angular7 so I could just call [routerLink]="myRouteName" instead of [routerLink]="/my/route/path".

If so, how can I achieve this?

Answer

Ashish Ranjan picture Ashish Ranjan · Dec 4, 2018

Considering you want to configure the routes names while you are creating the route configuration.

Lets leverage routes' data property to add names to routes. (A small extra data in every route should not affect any performance).

But first, let's create a class which conatains a static property for holding route names and their actual paths.

export class RouteNames {
  public static routeNamesObject = {}
}

Now in your routing component where you have defined the routes, let's have it like:

const routes: Routes = [
  {path: "hello/:id", component: HelloComponent, data: {routeName: "Hello1"}},
  {path: "hello", component: HelloComponent, data: { routeName: "Hello2" }}
]

Just after this variable initialization set the RouteNames class's static prop

routes.forEach((eachRoute) => {
  RouteNames.routeNamesObject[eachRoute.data.routeName] = eachRoute.path;    // now all route paths are added to this prop
})

Make a public variable in your component to access the static class

Like in app.component.ts: (You don't need injection)

public routeNames = RouteNames;

Then the app.component.html will be something like:

<button [routerLink]="routeNames.routeNamesObject['Hello2']">Click to Navigate to Hello</button>