[英]Display component data from nested routes - 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中,我有一个sidenav,其中包含3个组件(TodosComponent,AddTodosComponent,DeleteTodosComponent)的链接。
每当尝试从sidenav单击一个组件时,我试图在AppComponent的内容区域中显示三个组件的内容。 当我单击子路由时,我收到此错误: 无法匹配任何路由。 网址段:“待办事项/添加”
在sidenav中单击链接时,如何在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>
角度文档摘录
从技术上讲,当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},
]},
]
为什么需要孩子,因为我们将所有孩子都显示在同一个路由器插座中。
const appRoutes: Routes = [
{ path: '', redirectTo: '/todos', pathMatch: 'full' },
{ path: '/todos', component: TodosComponent },
{ path: '/todos/add', component: AddTodoComponent },
{ path: '/todos/delete', component: DeleteTodoComponent }
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.