Drakee510
Drakee510

Reputation: 500

Repeating Path on Angular's Router

I have a single component that I want to handle nested routes. I have a nested data structure that could potentially be infinite in length. Is there a way to create nested routes like the following below without having to manually create it in Angular's router? I am using Angular 6.

/items/{id}
/items/{id}/child/{id}
/items/{id}/child/{id}/child/{id}

Upvotes: 1

Views: 727

Answers (2)

Manoj De Mel
Manoj De Mel

Reputation: 995

I have solved my problem which was very similar to yours. This is the route configuration that I have used:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FolderDetailsComponent } from './folder-details.component';

    const routes: Routes = [
        {
            path: '',
            component: FolderDetailsComponent,
        },
        {
            path: 'folders/:folder_id', loadChildren: () =>
                import('./folder-details.module').then(m => m.FolderDetailsModule)            
        }];

    @NgModule({
        imports: [RouterModule.forChild(routes)],
        exports: [RouterModule]
    })
    export class FolderRoutingModule { }

This pattern will match path such as : /folders/1/folders/2/folders/3

Upvotes: 1

jburtondev
jburtondev

Reputation: 3263

Ultimately, the Routes are simply objects in an array of type Route:

const appRoutes: Routes = [
  { path: 'your-path', component: YourPathComponent },
];

Therefore if we define a function that pushes new objects into this array, then this will allow you to iterate through your data structure (you haven't mentioned what structure it is), and then push these objects into the array appRoutes in this case.

It will end up looking something like:

function generateRoutes(dataStructure: any) {
  // Extract data from your structure into your new array using Array.map() etc. 
  // Assuming we use a for the Array.map() function. 

  dataStructure.map((item: Route) => {
    return {
      path: item[0].path,
      component: item.component // You may need to cast this to the Component interface
    }
  })
}

const appRoutes: Routes = generateRoutes(routesData);

Upvotes: 1

Related Questions