Search code examples
angularroutesurl-routingangular2-routing

Adding dynamic routes in angular?


The routes for a page are coming from the API in the following format:

[{
    "name": "Contact",
    "url": "/customers/contact",
    "pages": [],
},
{
    "name": "Order",
    "url": "/customers/order",
    "pages": [
        {
            "name": "Stocks",
            "url": "/customers/order/stocks",
        },
        {
            "name": "Business",
            "url": "/customers/order/business",
        }
    ]
}]

What would be the best way to the the urls as paths in the routing module?

There's no point in hardcoding the urls as new languages will be added, the old ones might have updated paths.


Solution

  • Some ways:

    Easiest: use wildcards alà

    const routes: Routes = [
      { path: '**', component: DynamicComponent }
    ];
    

    and let the component (DynamicComponent in this case) handle the "route" and loading the view as example.

    Other way, but with little warning The resetConfig method in Router. (Link)

    constructor(private router: Router) {
      this.router.resetConfig(newRoutes);
    }
    

    With this you can create completely new routes. But (!!) if you change this you change all routes of you complete application. So be careful!