You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 { }

关键细节说明

  1. DefaultComponent 模板要求
    这个通用布局组件的模板里必须包含<router-outlet>标签,子路由的内容才会渲染到这里。示例模板如下:

    <!-- default.component.html -->
    <nav>站点导航内容</nav>
    <div class="main-content">
      <router-outlet></router-outlet> <!-- 子路由组件会在这里渲染 -->
    </div>
    <footer>通用页脚</footer>
    
  2. 子路由的层级关系
    /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' }
      ]
    }
    
  3. 独立路由的特殊性
    non-default是顶级路由,不属于DefaultComponent的子路由,所以访问/non-default时,Angular只会加载NonDefaultComponent,不会渲染通用导航。

内容的提问来源于stack exchange,提问作者Chris O'Brien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:43:38