I am having trouble routing in Angular 5.
I would like to support the following URL's
This one works:
/post
This one doesn't, it redirects me to my NotFoundComopnent
/post/test-post-title
My AppRoutingModule
export const routes: Routes = [
{ path: 'post', loadChildren: 'app/feature/post/post.module#PostModule' },
{ path: '**', component: NotFoundComponent },
];
export class AppRoutingModule { }
My PostRoutingModule:
const routes: Routes = [
{
path: '',
component: PostHomeComponent,
children: [
{
path: ':slug', component: PostDetailComponent
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PostRoutingModule { }
Updated to show the PostDetailComponent
export class PostDetailComponentimplements OnInit {
constructor(
private route: ActivatedRoute
) {}
ngOnInit() {
const id = +this.route.snapshot.paramMap.get('slug');
console.log(id)
}
}
In Angular, the router lets you add child routes using the children property inside the routing module.
The following covers routing for Angular 2+ apps. All you need to define child routes is to add an array of additional route configuration objects as part of a children key in your parent configuration. Here’s an example configuration: And don’t forget to add a router-outlet directive in the template of any parent component:
It’s easy to create any kind of routing hierarchy in your Angular apps by using child routes in your router configurations. The following covers routing for Angular 2+ apps. All you need to define child routes is to add an array of additional route configuration objects as part of a children key in your parent configuration.
Define your routes in your Routes array. Each route in this array is a JavaScript object that contains two properties. The first property, path, defines the URL path for the route. The second property, component, defines the component Angular should use for the corresponding path.
When you define a child route using "children: [{ ... }]" as in your PostRoutingModule, you must have a router outlet inside your PostHomeComponent for this child component to be injected in.
In other words, if Component B is child of Component A, you can't expect to inject them both into the same router outlet that you have on app level.
Either, have a router outlet inside PostHomeComponent - this may or may not be what you want as you would end up displaying both Parent and Child components at the same time.
Or, change your routes to this:
const routes: Routes = [
{
path: '',
component: PostHomeComponent
},
{
path: ':slug', component: PostDetailComponent
}
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With