angular子路由配置

子路由是组件下新增一个子路由组件,可以通过指令完成初始化

1
ng generate component crisis-center/crisis-center

把组件模板修改成这样:

1
2
<h2>CRISIS CENTER</h2>
<router-outlet></router-outlet>

CrisisCenterComponent 和 AppComponent 有下列共同点:

  • 它是危机中心特性区的根,正如 AppComponent 是整个应用的根。
  • 它是危机管理特性区的壳,正如 AppComponent 是管理高层工作流的壳。

完整例子

AppRoutingModule

1
2
3
4
5
6
7
8
9
const routes: Routes = [
{path:'',redirectTo:'/home',pathMatch:'full'},
{path:'home',component:HomeComponent},
{path:'product/:id',component:ProductComponent,children:[
{path:'',component:ProductDescComponent},
{path:'seller/:id',component:SellerInfoComponent}
]},
{path:'**',component:Code404Component}
];

productComponent

1
2
3
4
5
6
7
8
9
<p>
这是一个商品详情组件
</p>
<p>
商品ID是{{productId}}
</p>
<a [routerLink]="['./']">商品描述</a><br>
<a [routerLink]="['./seller',99]">销售员信息</a>
<router-outlet></router-outlet>

seller-info.component.html

1
2
3
<p>
销售员ID是{{sellerId}}
</p>

sellerInfoComponent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-seller-info',
templateUrl: './seller-info.component.html',
styleUrls: ['./seller-info.component.css']
})
export class SellerInfoComponent implements OnInit {
private sellerId:number;
constructor(private routeInfo:ActivatedRoute) { }

ngOnInit() {
this.sellerId = this.routeInfo.snapshot.params['id'];
}

}