routerLink 指令
基本概念
在 Angular 應用中,如果使用傳統的 href
來控制頁面導航,每次點擊連結時瀏覽器都會重新載入整個頁面,包含所有的 HTML 與 JavaScript 檔案,這樣會造成效能開銷大的問題。
因此 Angular 提供了 routerLink
指令,它有以下優點:
設定導航路徑時不會觸發頁面重載
Angular 會攔截預設的瀏覽器行為,避免重新獲取 HTML 文件
Angular 路由器接管導航過程,只渲染路徑對應的元件
保持在 SPA (Single Page Application) 的運作模式內
使用方式
基本用法:
<a routerLink="/heroes">英雄列表</a>
帶參數的路由:
<a [routerLink]="['/hero', hero.id]">{{ hero.name }}</a>
添加 active 樣式 (當前選中路由):
<a routerLink="/heroes" routerLinkActive="active">英雄列表</a>
相對路徑
routerLink
支援我們設置相對連結 (relative links),相對於當前啟動的路由。(前面沒有斜線!)
<a routerLink="tasks/new">Add Task</a>
上一級
以當前的路徑往上一級,也就是他會移除最後一個 segment。
<a routerLink="../">Cancel</a>
舉例: users/u3/tasks/new
→ users/u3/tasks
設定路由 (Standalone 寫法)
在 Angular 的 standalone 寫法中,設定路由不再需要單獨的模組檔案,可以直接在 main.ts
或 app.component.ts
中設定:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, Routes } from '@angular/router';
import { AppComponent } from './app/app.component';
import { HeroesComponent } from './app/heroes/heroes.component';
import { HeroDetailComponent } from './app/hero-detail/hero-detail.component';
const routes: Routes = [
{ path: 'heroes', component: HeroesComponent },
{ path: 'hero/:id', component: HeroDetailComponent },
{ path: '', redirectTo: '/heroes', pathMatch: 'full' }
];
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes)
]
});
通常會把 path 的設定拆出去成為獨立的檔案。
在 standalone 元件中,記得要引入 RouterLink 和 RouterOutlet:
// app.component.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink],
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/heroes">英雄列表</a>
</nav>
<router-outlet></router-outlet>
`
})
export class AppComponent {}
注意事項
在 standalone 元件中記得要引入
RouterLink
和RouterOutlet
在 HTML 模板中使用
<router-outlet></router-outlet>
作為路由組件的顯示位置可以使用
routerLinkActive
指令來設定當路由匹配時的 CSS 類使用 lazy loading 時,記得使用
loadComponent
或loadChildren
來引入路由
使用 routerLink
是 Angular 應用中實現導航的最佳實踐,它充分利用了單頁應用的特性,提供流暢的使用體驗同時優化效能。
Last updated