Implementing Dynamic Routing in Angular2 (Typescript)

darkdefender27 picture darkdefender27 · Jan 17, 2016 · Viewed 18k times · Source

RouteConfig class which can be used to decorate a component (@RouteConfig) with routing capabilities has certain route definitions defined for that component. Now, the catch is to have these route definitions injected at runtime (dynamically).

The reason being, let's say I have an application wherein I have to display (UI) and define (decorate) 'n' number of routes, each which corresponds to the account for which the application is loaded and consequently the rights that are associated with that particular account. Thus, having the route definitions pre-defined in the decorator @RouteConfig for a component doesn't make any sense.

My approach is to make a service call every time a new account is loaded. And retrieve the associated routes only and inject them during runtime so as to navigate to other respective components corresponding to each route displayed in the UI for that account.

import { Summary } from './components/summary';

@RouteConfig([
  /*
    Let's say we need a seller dashboard to be displayed...
  */
  //{ path: 'SellerDashboard', component: SellerDashboard }
  { path: '/', component: Summary }
])
class App {
    contactInfo: ContactInfoModel;
    public App(dataService: DataService) {
        this.model = dataService.getContactInfo();
    }
}

In the code snippet above, lets say I wish to load the seller dashboard corresponding to a seller account looged in to my application. Now, it won;t make any sense to display the Point of Sales dashboard or anything thats not relevant to a seller (In our case, seller's inventory dashboard is relevant to a seller).

In a gist, injecting only those routes that are required instead of configuring all the routes in the same place.

EDIT 1:

This question has a simple use case or a scenario than the duplicate marked on this post (which was asked afterwards). The answers mentioned in this post have simpler approaches and are far more intuitive, too.

Answer

Ma Jerez picture Ma Jerez · Mar 28, 2016

Check this post:

http://blog.mgechev.com/2015/12/30/angular2-router-dynamic-route-config-definition-creation/

Basically the author creates a class DynamicRouteConfigurator that uses the Reflect API to dynamically add routes to the @RouteConfig decorator.

Github link:

https://github.com/mgechev/dynamic-route-creator/blob/master/app/components/app/app.ts