Thibs
Thibs

Reputation: 8288

Angular 2: appending child routes dynamically

I would like to know if it is possible to dynamically append child routes at run time, from lets say a service...?

Given:

const routes: Routes = [
    {
        path: '', component: GloriousComponent,
        children: [
           { path: 'path1', component: Child1Component },
           { path: 'path2', component: Child2Component },
           { path: 'path3', component: Child3Component },
        ]
    }
];

Could I remove the children of the ' ' path and somehow get a reference to the const routes and then later on dynamically append children to the ' ' path?

Something along the lines of...

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

routes[''].appendChildren(
        [
           { path: 'path1', component: Child1Component },
           { path: 'path2', component: Child2Component },
           { path: 'path3', component: Child3Component },
        ]
    )

Upvotes: 7

Views: 4557

Answers (2)

KHAN
KHAN

Reputation: 115

As of now, achieving this is easy. If you want to add a child route to the current route,

const childRoute =  {path: 'details', component: DetailsComponent} 
this.route.routeConfig.children.push(childRoute)

where "this.route" is from the ActivatedRoute injected in the constructor:

constructor(private router: Router, private route:ActivatedRoute) { }

Alternatively, if you just want to add a new route to the router config, do this:

newRoute = {path: 'somePath', component: SomeComponent}
this.router.config.push(newRoute)

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657821

Currently modifying is not supported but you can maintain a list of routes yourself and then call

this.router.resetConfig(routes)

to load a new set of routes into the router.

Upvotes: 6

Related Questions