動態路徑參數

定義動態路徑

在 Angular 路由設定中,我們可以使用冒號 : 來定義動態路徑參數。這讓我們能夠建立可接受變數值的路由。

// 在路由配置文件中定義動態路徑
const routes: Routes = [
  { 
    path: 'users/:userId',
   component: UserDetailComponent 
  },
  { 
    path: 'heroes/:heroId/details', 
    component: HeroDetailsComponent 
  }
];

這裡的 :userId:heroId 就是動態路徑參數,它們可以匹配任何值。

使用動態路徑

在 HTML 模板中,有兩種方式可以導航到動態路徑:

1. 字串串接方式

使用模板表達式和字串串接來構建完整的 URL:

<a [routerLink]="'/users/' + user().id" routerLinkActive="selected">
  用戶詳情
</a>

注意這裡使用的是屬性綁定 [routerLink],而不是直接的 routerLink 指令,因為我們需要動態計算路徑。

2. 陣列方式(推薦)

使用陣列來表示路徑段,Angular 會自動在各段之間添加斜槓:

<a [routerLink]="['/users', user().id]" routerLinkActive="selected">
  用戶詳情
</a>

這種方式的優點:

  • 不需要手動管理斜槓

  • 更容易處理複雜的巢狀路徑

  • 程式碼更加清晰易讀

對於多層級的路徑,陣列方式尤其方便:

<a [routerLink]="['/heroes', hero().id, 'details', 'powers']">
  英雄能力詳情
</a>

這會產生 /heroes/{id}/details/powers 的 URL。

在元件中獲取動態參數

在目標元件中,我們可以透過 ActivatedRoute 服務來獲取路徑參數:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user-detail',
  standalone: true,
  template: `<h2>用戶 ID: {{userId}}</h2>`
})
export class UserDetailComponent implements OnInit {
  userId: string = '';

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    // 方法 1: 使用快照 (只取一次值)
    this.userId = this.route.snapshot.paramMap.get('id') || '';

    // 方法 2: 使用 observable (響應式,參數變化時會更新)
    this.route.paramMap.subscribe(params => {
      this.userId = params.get('id') || '';
    });
  }
}

注意事項

  • 在 standalone 元件中使用動態路徑時,記得引入 RouterLinkRouterLinkActive

  • 如果有多個動態參數,可以在陣列中依序添加

  • 使用 observable 方式獲取參數時,記得在元件銷毀時取消訂閱,避免記憶體洩漏

  • 路徑參數總是字串類型,如需使用數字,要進行轉換

Last updated