Search code examples
angularroutesdynamicprimeng

Create dynamic paths in my routing - Angular / PrimeNg version


I need to create several paths dynamically in my routing since the values ​​will be added to the sidebars through an endpoint.

By creating a new item for the sidebar, the user will be specifying the path values ​​for each menu.

The value for the path entered by the user is the one that should be added in the routing.

All paths will be using the same component but the data to be displayed is validated by the path

loadDynamicRoutes() {
    this.routesService.getRoutes().subscribe((routes: any[]) => {
      const dynamicRoutes = routes.map(route => ({
        path: route.path,
        component: AdminRolesComponent
      }));

      this.router.resetConfig([...staticRoutes, ...dynamicRoutes]);
    });
  }

This is an example of my code but I don't know how to add it to the routing.

Is there an easier way to leave my sidebar and paths dynamic?


Solution

  • The code seems to work fine, We can just generate the paths, then use resetConfig to make the routes dynamic. Please find below working example (forked) highlighting this dynamic behaviour.

    import { Component } from '@angular/core';
    import { Router, Routes } from '@angular/router';
    import { routes } from './app.routing.module';
    import { Observable, of } from 'rxjs';
    import { RouteOneComponent } from './route-one/route-one.component';
    import { RouteTwoComponent } from './route-two/route-two.component';
    import { RouteThreeComponent } from './route-three/route-three.component';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      routes = routes;
    
      constructor(private router: Router) {}
    
      ngOnInit() {
        // Initial routes
        console.log(this.routes);
        this.changeRouteConfig();
      }
    
      changeRouteConfig() {
        this.getUrl().subscribe((data: Routes) => {
          // Updated routes
          console.log(data);
          this.routes = data;
          this.router.resetConfig(data);
        });
      }
    
      getUrl(): Observable<Routes> {
        return of([
          { path: 'route-one', component: RouteOneComponent },
          { path: 'route-two', component: RouteTwoComponent },
          { path: 'route-three', component: RouteThreeComponent },
        ]);
      }
    }
    

    Stackblitz Demo (forked - not by me)