如何在Angular 5中配置两层以上的嵌套子路由?
Hey there! Let's get that nested routing working perfectly for your app. Based on your component folder structure (John → Mark → James) and desired URL https://my-website/john-route/mark-route/james-route, here's the step-by-step solution:
Correct Route Configuration
First, update your module's route array to match the nested structure. Here's the full code:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; // Make sure your component paths match your folder structure! import { JohnComponent } from './john/john.component'; import { MarkComponent } from './john/mark/mark.component'; import { JamesComponent } from './john/mark/james/james.component'; const routes: Routes = [ { path: 'john-route', component: JohnComponent, children: [ { path: 'mark-route', component: MarkComponent, children: [ // This maps the final segment to JamesComponent { path: 'james-route', component: JamesComponent } ] } ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], // Use forRoot() if this is your root module exports: [RouterModule] }) export class YourFeatureModule { }
Critical Things to Remember
- Add
<router-outlet>to Parent Components: Nested routes need a place to render their child components.- In
john.component.html, add<router-outlet></router-outlet>— this is where MarkComponent will load when you navigate to/john-route/mark-route. - In
mark.component.html, add another<router-outlet></router-outlet>— this is where JamesComponent will load for the final path segment.
- In
- Double-Check Component Imports: Ensure all three components are declared in your module's
declarationsarray, and their file paths are correct (since Mark is in John's folder, and James is in Mark's, the import paths should reflect that).
Optional: Add Default Routes
If you want to redirect users to the next level automatically (e.g., /john-route loads Mark, /john-route/mark-route loads James), add these redirect routes:
const routes: Routes = [ { path: 'john-route', component: JohnComponent, children: [ // Redirect /john-route to /john-route/mark-route { path: '', redirectTo: 'mark-route', pathMatch: 'full' }, { path: 'mark-route', component: MarkComponent, children: [ // Redirect /john-route/mark-route to /john-route/mark-route/james-route { path: '', redirectTo: 'james-route', pathMatch: 'full' }, { path: 'james-route', component: JamesComponent } ] } ] } ];
Once you've set this up, navigating to https://my-website/john-route/mark-route/james-route will load JamesComponent inside MarkComponent, which in turn loads inside JohnComponent — exactly what you're looking for!
内容的提问来源于stack exchange,提问作者Jay Marz

