Scipion
Scipion

Reputation: 11888

Angular2 Organizing routing module

Here us my routing module.

@NgModule({
    imports: [
        RouterModule.forChild([
            {
                path: "",
                component: AdminComponent,
                children: [
                    {
                      path: "users",
                      component: ParentComponent
                      children: [
                        {
                          path: ":id",
                          component: AnotherComponent
                         }
                      ]
                    }
                ]
            }]
        )
    ],
    exports: [
        RouterModule
    ]
})

export class AdminRoutingModule {}

By doing so, I need to specify in my ParentComponent a <router-outlet></router-outlet>. The only problem here is that AnotherComponent isn't a part of ParentComponent, these are two different pages. So maybe a better structure would be to have them at the same level. The reason why I went for the that structure was because AnotherComponent can only be reached from the ParentComponent. What's the most sensible thing to do in here ?

Upvotes: 1

Views: 48

Answers (2)

slaesh
slaesh

Reputation: 16917

So as you already mentioned in your question, your router-config should look like this:

RouterModule.forChild([{
    path: "",
    component: AdminComponent,
    children: [
        {
          path: "users",
          component: ParentComponent
        },
        {
          path: "users/:id", /* OR WHATEVER .. */
          component: AnotherComponent,
          /* OPTIONAL GUARD */
          canActivate: [YourRouteGuard]
        }
    ]
}])

How and where you place your routerLink's is your part! :)

If you want to "protect" routes, you should use Guards!

https://angular.io/docs/ts/latest/guide/router.html#!#milestone-5-route-guards

Upvotes: 1

Faly
Faly

Reputation: 13346

Putting AnotherComponent at the same level as ParentComponent doesn't prevent AnotherComponent to be only reached from ParentComponent.

Upvotes: 0

Related Questions