gpt4 book ai didi

javascript - 显示来自嵌套路由的组件数据 - Angular

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:18 26 4
gpt4 key购买 nike

我有以下组件:

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>

Add 和 Delete 是 Todos 中的嵌套路由。

在我的主要 AppComponent 中,我有一个带有 3 个组件(TodosComponent、AddTodosComponent、DeleteTodosComponent)链接的 sidenav。

我试图在 AppComponent 的内容区域中显示 3 个组件的内容,无论何时从 sidenav 中单击一个组件。当我单击子路由时,我收到此错误:无法匹配任何路由。网址段:“todos/add”

当在 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>

我想要实现的目标: enter image description here

最佳答案

摘自 angular documentation

Technically, pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match ''.

在您的示例中,在路径 todos 中,剩余的未匹配部分是 /todos/add,这不是完全匹配,路由器不会查看里面的 child 并跳到下一条路径(你没有),当没有找到时,你会得到你得到的错误:)

/todos 路径中删除 pathMatch: 'full' 它应该可以工作:

const appRoutes: Routes = [
{ path: '', redirectTo: '/todos', pathMatch: 'full' },
{ path: 'todos', component: TodosComponent, children: [
{ path: 'add', component: AddTodoComponent},
{ path: 'delete', component: DeleteTodoComponent},
]},
]

关于javascript - 显示来自嵌套路由的组件数据 - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53089083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com