路由嵌套
- 新建需要用到组件
# 为便于看出welcome组件属于home的子组件,将welcome建在home组件的文件夹中
ng g component components/home
ng g component components/home/welcome
ng g component components/home/setting
ng g component components/product
ng g component components/product/pcate
ng g component components/product/plist
- 在style.less中定义全局样式
.content {
width: 100%;
height: 500px;
display: flex;
.left {
width: 200px;
border-right: 1px solid #eee;
height: 500px;
}
.right {
flex: 1px;
}
}
- 在路由模块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 { }
4.
在app.component.html跳转到home和product路由
```html
<h2>根组件</h2>
<header class='header'>
<a [routerLink]="[ '/home' ]" routerLinkActive="aaa">首页</a>
<a [routerLink]="[ '/product' ]" routerLinkActive="aaa">商品</a>
</header>
<router-outlet></router-outlet>
在home.component.html跳转到welcome、setting子路由
<div class="content">
<div class="left">
<a [routerLink]="[ '/home/welcome' ]">欢迎首页</a>
<br><br>
<a [routerLink]="[ '/home/setting' ]">系统设置</a>
</div>
<div class="right">
<!-- welcome、setting路由内容在此处输出 -->
<router-outlet></router-outlet>
</div>
</div>
在product.component.html跳转到pcate、plist子路由
<div class="content">
<div class="left">
<a [routerLink]="[ '/product/pcate' ]">商品分类列表</a>
<br><br>
<a [routerLink]="[ '/product/plist' ]">商品列表</a>
</div>
<div class="right">
<router-outlet></router-outlet>
</div>
</div>