Angular 5子路由配置:添加括号及默认组件路由结构实现
嘿,我来帮你搞定这个Angular 5的路由配置问题!根据你的需求,我们可以通过路由嵌套的方式实现DefaultComponent的复用,同时让/non-default路由独立出来不加载通用导航。下面是具体的实现方案:
核心思路
我们把DefaultComponent作为一个通用布局容器(包含站点导航等元素),让所有需要显示通用布局的页面作为它的子路由;而/non-default作为顶级独立路由,直接加载自己的组件,不依赖通用布局。
完整路由配置代码
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { DefaultComponent } from './default/default.component'; import { OverviewComponent } from './my-account/overview/overview.component'; import { MyStuffComponent } from './my-account/my-stuff/my-stuff.component'; import { ProfileComponent } from './profile/profile.component'; import { NonDefaultComponent } from './non-default/non-default.component'; const routes: Routes = [ // 所有需要通用布局的路由都嵌套在DefaultComponent下 { path: '', component: DefaultComponent, children: [ // my-account 子路由组 { path: 'my-account', children: [ { path: 'overview', component: OverviewComponent }, // 对应 /my-account/overview { path: 'my-stuff', component: MyStuffComponent }, // 对应 /my-account/my-stuff // 可选:访问/my-account时自动跳转到overview首页 { path: '', redirectTo: 'overview', pathMatch: 'full' } ] }, // 独立的profile路由 { path: 'profile', component: ProfileComponent }, // 对应 /profile // 可选:根路径直接重定向到首页 { path: '', redirectTo: 'my-account/overview', pathMatch: 'full' } ] }, // 不使用通用布局的独立路由 { path: 'non-default', component: NonDefaultComponent }, // 对应 /non-default // 可选:404页面重定向处理 { path: '**', redirectTo: 'my-account/overview' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
关键细节说明
DefaultComponent 模板要求
这个通用布局组件的模板里必须包含<router-outlet>标签,子路由的内容才会渲染到这里。示例模板如下:<!-- default.component.html --> <nav>站点导航内容</nav> <div class="main-content"> <router-outlet></router-outlet> <!-- 子路由组件会在这里渲染 --> </div> <footer>通用页脚</footer>子路由的层级关系
/my-account/overview和/my-account/my-stuff被嵌套在my-account路由下,如果你需要给my-account也加一个父组件(比如专属子导航),可以给my-account路由添加component属性,再在该组件里放一个<router-outlet>:// 修改my-account路由配置 { path: 'my-account', component: MyAccountComponent, // 新增的my-account父组件 children: [ { path: 'overview', component: OverviewComponent }, { path: 'my-stuff', component: MyStuffComponent }, { path: '', redirectTo: 'overview', pathMatch: 'full' } ] }独立路由的特殊性
non-default是顶级路由,不属于DefaultComponent的子路由,所以访问/non-default时,Angular只会加载NonDefaultComponent,不会渲染通用导航。
内容的提问来源于stack exchange,提问作者Chris O'Brien
相关产品推荐
相关产品推荐

