javascript - 显示来自嵌套路由的组件数据 - Angular
我有以下组件:
TodosComponent(路径:'./todos/'):包含 HTML 内容 <p>TODO WORKS</p>
AddTodosComponent (路径:'./todos/add'):带有 HTML 内容 <p>ADD TODO WORKS</p>
DeleteTodosComponent (路径:'./todos/delete'):带有 HTML 内容 <p>DELETE TODO WORKS</p>
添加和删除是 Todos 中的嵌套路由。
在我的主 AppComponent 中,我有一个带有三个组件链接(TodosComponent、AddTodosComponent、DeleteTodosComponent)的侧边导航栏。
我正在尝试在 AppComponent 的内容区域显示 3 个组件的内容,每当从侧边导航点击其中一个时。当我点击子路由时,我收到以下错误:无法匹配任何路由。URL 段:'todos/add'
当在侧边导航中点击链接时,我如何在 AppComponent 的 sidenav-content 中显示组件的 HTML?
app-routing.module.ts
const appRoutes: Routes = [
{ path: '', redirectTo: '/todos', pathMatch: 'full' },
{ path: 'todos', component: TodosComponent, pathMatch: 'full', children: [
{ path: 'add', component: AddTodoComponent},
{ path: 'delete', component: DeleteTodoComponent},
]},
]
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
app.component.html
<mat-sidenav-container>
<mat-sidenav opened="true" mode="side" fixedInViewport="true">
<p>I am the sidenav</p>
<mat-nav-list>
<mat-list-item>
<a matLine routerLink="/todos">List Todos</a>
</mat-list-item>
<mat-list-item>
<a matLine routerLink="/todos/add">Add Todo</a>
</mat-list-item>
<mat-list-item>
<a matLine routerLink="/todos/delete">Delete Todo</a>
</mat-list-item>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
<router-outlet></router-outlet>
<p>Main Content</p>
</mat-sidenav-content>
</mat-sidenav-container>
我想要实现的目标:
答案#1
摘自 Angular 文档
从技术上讲,当 URL 剩余的未匹配片段匹配空字符串时,pathMatch='full' 会导致路由命中。
在你的示例中,在路径 todos 上,剩余的未匹配部分是 /todos/add,这不是完全匹配,路由器不会检查其中的子路由,而是跳到下一个路径(你没有任何下一个路径),当没有找到时,你就会得到你遇到的错误 :)
从 /todos 路径中移除 pathMatch: 'full',它应该可以工作:
const appRoutes: Routes = [
{ path: '', redirectTo: '/todos', pathMatch: 'full' },
{ path: 'todos', component: TodosComponent, children: [
{ path: 'add', component: AddTodoComponent},
{ path: 'delete', component: DeleteTodoComponent},
]},
]
答案#2
为什么我们需要子组件,因为我们在同一个 router-outlet 中显示所有内容。
const appRoutes: Routes = [
{ path: '', redirectTo: '/todos', pathMatch: 'full' },
{ path: '/todos', component: TodosComponent },
{ path: '/todos/add', component: AddTodoComponent },
{ path: '/todos/delete', component: DeleteTodoComponent }
]
