路由嵌套

  1. 新建需要用到组件
    1. # 为便于看出welcome组件属于home的子组件,将welcome建在home组件的文件夹中
    2. ng g component components/home
    3. ng g component components/home/welcome
    4. ng g component components/home/setting
    5. ng g component components/product
    6. ng g component components/product/pcate
    7. ng g component components/product/plist
  1. 在style.less中定义全局样式
    1. .content {
    2. width: 100%;
    3. height: 500px;
    4. display: flex;
    5. .left {
    6. width: 200px;
    7. border-right: 1px solid #eee;
    8. height: 500px;
    9. }
    10. .right {
    11. flex: 1px;
    12. }
    13. }
  1. 在路由模块app-routing.module.ts中定义路由 ```typescript import { NgModule } from ‘@angular/core’; import { Routes, RouterModule } from ‘@angular/router’;

// 引入相关组件,为方便查看,建议子组件向后缩进 import { HomeComponent } from ‘./components/home/home.component’; import { WelcomeComponent } from ‘./components/home/welcome/welcome.component’; import { SettingComponent } from ‘./components/home/setting/setting.component’; import { ProductComponent } from ‘./components/product/product.component’; import { PcateComponent } from ‘./components/product/pcate/pcate.component’; import { PlistComponent } from ‘./components/product/plist/plist.component’;

// 配置路由 const routes: Routes = [ { path: ‘home’, component: HomeComponent, // 配置子路由,children内容格式同routes children: [ {path: ‘welcome’, component: WelcomeComponent}, {path: ‘setting’, component: SettingComponent}, {path: ‘‘, redirectTo: ‘welcome’} ] }, { path: ‘product’, component: ProductComponent, children: [ {path: ‘pcate’, component: PcateComponent}, {path: ‘plist’, component: PlistComponent}, {path: ‘‘, redirectTo: ‘plist’} ] }, { path: ‘**’, redirectTo: ‘home’ } ];

@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

  1. 4.
  2. app.component.html跳转到homeproduct路由
  3. ```html
  4. <h2>根组件</h2>
  5. <header class='header'>
  6. <a [routerLink]="[ '/home' ]" routerLinkActive="aaa">首页</a>
  7. <a [routerLink]="[ '/product' ]" routerLinkActive="aaa">商品</a>
  8. </header>
  9. <router-outlet></router-outlet>
  1. 在home.component.html跳转到welcome、setting子路由

    1. <div class="content">
    2. <div class="left">
    3. <a [routerLink]="[ '/home/welcome' ]">欢迎首页</a>
    4. <br><br>
    5. <a [routerLink]="[ '/home/setting' ]">系统设置</a>
    6. </div>
    7. <div class="right">
    8. <!-- welcome、setting路由内容在此处输出 -->
    9. <router-outlet></router-outlet>
    10. </div>
    11. </div>
  1. 在product.component.html跳转到pcate、plist子路由

    1. <div class="content">
    2. <div class="left">
    3. <a [routerLink]="[ '/product/pcate' ]">商品分类列表</a>
    4. <br><br>
    5. <a [routerLink]="[ '/product/plist' ]">商品列表</a>
    6. </div>
    7. <div class="right">
    8. <router-outlet></router-outlet>
    9. </div>
    10. </div>