Routing With ID in Angular 4

Joseph picture Joseph · Aug 27, 2017 · Viewed 31.3k times · Source

I need help in my routing in Angular 4. I want to display the URL like this. Localhost:4200/user/1 if i clicked the view details of the first user. I'm a bit confused on how to to this. I've tried my best in my code below but it still doesn't work.

app-routing.module.ts

const appRoutes: Routes = [
    { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
    { path: 'dashboard', component: DashboardComponent },
    { path: 'user', component: UserComponent, children: [

        { path: 'create-new-user', component: CreateNewUserComponent },
        { path: 'user-list', component: UserListComponent },
        { path: 'user-detail/:id', component: UserDetailComponent },

]},
];


@NgModule({
    imports: [RouterModule.forRoot(appRoutes)],
    exports: [RouterModule]
})
export class AppRoutingModule {

}

Answer

Jandro Rojas picture Jandro Rojas · May 17, 2018

I had this very problem a while ago. The problem here is the routes configurations you have. You cannot go to /user/1 because you defined the 'user-details' route as a child of the 'user' route. You either have to navigate to '/user/user-detail/1' or simply define a new child route with path ':id' pointing to your details component and you'll be able now to navigate to '/user/1'.

To sum up: With the routes:

const appRoutes: Routes = [
    ...
    { path: 'user', component: UserComponent, children: [

        ...
        { path: 'user-detail/:id', component: UserDetailComponent },

    ]},
];

you can navigate to '/user/user-details/1'. With the routes:

const appRoutes: Routes = [
    ...
    { path: 'user', component: UserComponent, children: [

        ...
        { path: ':id', component: UserDetailComponent },

    ]},
];

you can navigate to '/user/1'. Hope it helps you.