Reputation: 41
I have a problem regarding the routing in Angular 5. I would like to create a child route but when i type the url (for child route) the parent component gets loaded. My routing:
path: 'user-admin/:id',
component: UserAdminComponent,
},
children: [
{
path: '',
component: UserAdminComponent,
pathMatch: 'full'
},
{
path: "final-exams",
component: FinalExamsComponent,
},
The two routes that belongs to the problem:
http://localhost:4200/user-admin/0
http://localhost:4200/user-admin/0/final-exams
Thank you for your help in advance! :)
Upvotes: 3
Views: 1756
Reputation: 737
Here in this case you dont need to add a child route to UserAdminComponent and open/close braces as follows. Try this code.
{ path: user-admin/:id', component: UserAdminComponent,
children: [
{ path: 'final-exams', component: FinalExamsComponent},
//add child routes here
]
},
Upvotes: 0
Reputation: 1732
Have a look at the working solution
user-admin/1 // Hello will be printed
user-admin/1/final-exams // Hola will be the output
Problem was:
You mentioned the same component in both Parent and Child Route & Children routes were not mentioned inside the parent route
const appRoutes: Routes = [
{
path: 'user-admin/:id',
// component: HelloComponent, // No need to mention the same component, in parent
children: [ // Children routes are inside the parent route
{
path: '',
component: HelloComponent,
pathMatch: 'full'
},
{
path: "final-exams",
component: HolaComponent
}
]
}
];
Upvotes: 2
Reputation: 3724
If the route final-exams
and its content found in FinalExamsComponent
need to be rendered alongside the content of UserAdminComponent
, you can use component less routes to achieve what you require. Like so
{
path: 'user-admin/:id',
component: UserAdminComponent,
children: [
{ path: ''},
{ path: "final-exams", component: FinalExamsComponent },
]
}
This way, when you go to http://localhost:4200/user-admin/0 you will only render UserAdminComponent
associated with user-admin/:id
alone. Accessing http://localhost:4200/user-admin/0/final-exams would then render both the content of UserAdminComponent
and of FinalExamsComponent
You can read about component less routes here.
Upvotes: 0
Reputation: 15619
You're closing the path before allowing the children to come into it:
{
path: 'user-admin/:id',
component: UserAdminComponent,
children: [
{path: '', component: UserAdminComponent, pathMatch: 'full'},
{path: 'final-exams', component: FinalExamsComponent},
]
},
At the moment, you're putting a }
before you start children
.
Upvotes: 0