Named Route

Why do we not name Angular routes?

When we want to write a link in Angular templates, then we usually use RouterLink. For example, if you want this link "/user/1/bookmark/1234/detail" in a templates, you might write it useing RouterLink as follows:

<a [routerLink]="['/user', user.id, '/bookmark', bookmark.id, '/detail']">

But in this approach, we have to write all of the path components to templates. Then actually we have already registered the path to Router through the RouterModule. So I thought that we can reuse them.

How can I write links in templates like a template tag of Django? Yes, we need a route's name.

We need Named Route.

import { Route } from '@angular/router';

export interface NamedRoute extends Route {
  name?: string;
}

export type NamedRoutes = NamedRoute[];

This is NamedRoute interface and NamedRoutes type implementations. The NamedRoute is just the Route interface extended with name property. I use this interface in this website for reversing url by name. For example:

<a [appUrl]="['article', article.id]">{{ article.title }}</a>

is rendered as follows:

<a href="/blog/123456789">Title</a>

The RouterLink needs all path components for reversing. It's the same way to write that full path, isn't it?🤔

<a [routerLink]="['/user', user.id, '/bookmark', bookmark.id, '/detail']">

But if you use the NamedRoute, you don't have to write all components just like this.

export const myRoutes: NamedRoutes = [
    ...
    { path: '/user/:userId/bookmark/:bookmarkId/detail', component: BookmarkDetailComponent, name: 'bookmarkDetail' },
    ...
];
...
imports: [RouterModule.forRoot(myRoutes)],
...
<a [appUrl]="['bookmarkDetail', user.id, bookmark.id]">

And in the middle of development, route's path are something changed. But as long as values and the order is not changed, you don't have to fix templates.

-   { path: '/user/:userId/bookmark/:bookmarkId/detail', component: BookmarkDetailComponent, name: 'bookmarkDetail' },
+   { path: '/users/:userId/bookmarks/:bookmarkId/detail', component: BookmarkDetailComponent, name: 'bookmarkDetail' },

This implementation is just experimentally. The appUrl directive searchs route from given name, replaces path components that started with ":" to given values, and returns the replaced path. The appUrl directive receives array of path which composed by name and values, but also there is another idea that it receives path name, key and value object like this:

<a [appUrl]="{name: 'bookmarkDetail', params: {userId: user.id, bookmarkId: bookmark.id}}">

See also: Vue.js/Vue Router: Named Routes.

If there's something, please ask me @tanb.