1. 程式人生 > 程式設計 >詳解Angular路由之子路由

詳解Angular路由之子路由

一、子路由語法

詳解Angular路由之子路由

二、例項

在商品詳情頁面,除了顯示商品id資訊,還顯示了商品描述,和銷售員的資訊。

通過子路由實現商品描述元件和銷售員資訊元件展示在商品詳情元件內部。

1、新建2個元件修改其內容

ng g component productDesc
ng g component sellerInfo

重點是修改銷售員資訊元件,顯示銷售員ID。

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"]; } }

2、修改路由配置

給商品元件加上子路由

const routes: Routes = [
  { path: '',rediwww.cppcns.com
rectTo : 'home',pathMatch:'full' },//路徑為空 { path: 'home',component: HomeComponent },{ path: 'product/:id',component: ProductComponent,children:[ { path: '',component : ProductDescComponent },{ path: 'seller/:id',component : SellerInfoComponent } ] },{ path: '**',component: Code404Component } ];

3、修改product.component.ts的模版

注意:routerLink裡要配置成./,不能再用/。

<p>
  這裡是商品資訊元件
</p>
<p>
  商品id是: {{productId}}
</p>

<a [routerL程式設計客棧ink]="['./']">商品描述</a>
<a [routerLink]="['./seller',99]">銷售員資訊</a>
<router-outlet></router-outlet>

效果:

主路由是/product/2,子路由為空字串:

主路由的商品詳情元件顯示出來了,子路由的空字串對應的商品描述元件也顯示出來了。

詳解Angular路由之子路由

點銷售員資訊連結:

URL路徑變成:http://localhost:4201/product/2/seller/99。

子路由seller/99,對應的sellerInfo組程式設計客棧xPaAnh件也展示出來。

詳解Angular路由之子路由

注意:

1、插座router-out形成父子關係,可以無限巢狀

詳解Angular路由之子路由

2、所有的路由資訊都是在模組層,在app.routing.moxPaAnhdule.ts中配置的。

路由資訊都是在模組層,所有的元件本身,並不知道任何跟路由相關的資訊。

插座之間的父子關係——子路由。

插座之間的兄弟關係——輔助路由。

以上就是詳解Angular路由之子路由的詳細內容,更多關於Angular的資料請關注我們其它相關文章!