Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 703
RafaelTSCS Avatar asked Dec 04 '18 14:12

RafaelTSCS


People also ask

How do you define routes in Angular?

Define your routes in your Routes array. Each route in this array is a JavaScript object that contains two properties. The first property, path , defines the URL path for the route. The second property, component , defines the component Angular should use for the corresponding path.

Which method is used to create route definitions in Angular?

forRoot(routes) ], The method is called forRoot() because you configure the router at the application's root level. The forRoot() method supplies the service providers and directives needed for routing, and performs the initial navigation based on the current browser URL.

What is default routing in Angular?

Default is "/" (the root path). The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'. By default, the router checks URL elements from the left to see if the URL matches a given path and stops when there is a config match.

What is route parameters in Angular?

To access the route parameters, we use route. snapshot , which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.


3 Answers

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>
like image 137
Ashish Ranjan Avatar answered Oct 17 '22 17:10

Ashish Ranjan


<a [routerLink]="routerLinkVariable"></a>

So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below

export class myComponent {

     public routerLinkVariable = "/my/route/path"; // the value of the variable is string!
}
like image 7
Mile Mijatović Avatar answered Oct 17 '22 18:10

Mile Mijatović


I managed to do this like this (bonus if someone can tell me how to remove the Array loop):

custom-route.interface.ts -- this is to add name to our route object


export interface ICustomRoute extends Route {

  name?: string;

}

In routing.module.ts (or wherever you have stored your routes):

const routes: ICustomRoute[] = [
  { path: 'some/random/page1', component: TestComponent, name: 'page1'  },
  { path: 'some/random/page2', component: Test2Component, name: 'page2'  },
  { path: 'page3', component: Test3Component, name: 'page3'  },
];

Now the name is being passed into your routing module so now you have to catch the name and handle it. You can do this in a number of ways, I ended up using a directive (I saw @Safron mentioned a pipe as well)

named-routerlink.directive.ts

@Directive({
  selector: 'a[namedRouterLink]'
})
export class NamedRouterLinkDirective extends RouterLinkWithHref{
  @Input('namedRouterLink')

  set namedRouterLink(val: any) {
    const selectedRoute = this.myRoute.config.filter( x => x['name'] == val)[0];
    this.routerLink = "/" + selectedRoute['path']
  };

  constructor(router: Router, route: ActivatedRoute, locationStrategy: LocationStrategy, private myRoute: Router){
    super(router, route, locationStrategy)
  }

}

And then obviously use like this:

 <a namedRouterLink="page1">Page 1</a>

Pipe Version:

@Pipe({name: 'getRoute' })
export class RoutePipe implements PipeTransform {

  constructor(private router: Router){}

  transform(routeName: string): string {
    const selectedRoute = this.router.config.filter( x => x['name'] == routeName)[0];
    return "/" + selectedRoute['path']
  }

}

Pipe Example:

 <a namedRouterLink="{{ 'page1' | getRoute }}">Page 1</a>
like image 5
PreQL Avatar answered Oct 17 '22 16:10

PreQL