I'm new to angular and i'm trying to understand the routing process with child routes. As described here (https://angular.io/guide/router#milestone-4-crisis-center-feature), i want to have different app-features in separate feature modules with separate routing modules.
Within these routing modules i configured some child routes and i have a navbar (in feature.component.html) with some routerLinks that are relative (without a '/' in the first segment, see https://angular.io/api/router/RouterLink). However this is not working as expected. Instead of switching between localhost:4200/child and localhost:4200/grandchild, it tries to go from localhost:4200/child to localhost:4200/child/grandchild; I would like to understand why this is happening. With an absolute routerLink like '/child' it works; But as far as is understand routing it should also work without the leading slash because the router then checks for children, based on the activated route
taken from the official Angular Doc:
The first segment name can be prepended with /, ./, or ../:
- If the first segment begins with /, the router will look up the route from the root of the app.
- If the first segment begins with ./, or doesn't begin with a slash, the router will instead look in the children of the current activated route.
- And if the first segment begins with ../, the router will go up one level.
feature.component.ts (NgModule only)
@NgModule({
declarations: [
FeatureComponent,
ChildComponent,
GrandchildComponent
],
imports: [
CommonModule,
FeatureRoutingModule
]
})
feature.component.html
<div class="border border-primary">
<h1>feature.component</h1>
<div>
<nav class="navbar navbar-expand bg-dark navbar-dark">
<div class="navbar-nav">
<a class="nav-item nav-link" routerLink="child">CHILD</a>
<a class="nav-item nav-link" routerLink="grandchild">GRANDCHILD</a>
</div>
</nav>
</div>
<router-outlet></router-outlet>
</div>
feature-routing.module.ts(routes only)
const routes: Routes = [
{
path: '', component: FeatureComponent, children:
[
{ path: 'child', component: ChildComponent },
{ path: 'grandchild', component: GrandchildComponent }
]
}
];
app.component.html
<h1>app.component</h1>
<router-outlet></router-outlet>
app-module.ts (NgModule only)
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FeatureModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
- on the first load i see the feature component with the navbar. The Url says: localhost:4200
- first click on 'CHILD' = The URL changes to localhost:4200/child -->this is ok for now
- second click on 'GRANDCHILD', it tries to go to localhost:4200/child/(grandchild), taken from the console output:
NavigationError {id: 32, url: "/child/(grandchild)", error: Error: Cannot match any routes. URL Segment: 'child' at ApplyRedirects.push../node_modules/@angu…}
Why is this happening? how can i output the activated route in the console to understand everything a little bit better?