Angular Router は URL パスをコンポーネントにマップし、シングルページアプリケーションでのページ全体をリロードしないナビゲーションを実現します。パスをコンポーネントに関連付けるルート設定配列を定義します。
ルートを定義する
ts
{ } ;
: = [
{ : , : },
{ : , : },
{ : , : },
{ : , : ().( m.) },
{ : , : },
];
<!-- the router renders the matched component here -->
<router-outlet></router-outlet>
<a routerLink="/users" routerLinkActive="active">Users</a>
<a [routerLink]="['/users', user.id]">View {{ user.name }}</a> <!-- dynamic path -->
routerLink はクライアント側のナビゲーション (リロードなし) を実行し、routerLinkActive はリンクのルートがアクティブな場合に CSS クラスを追加します — ナビゲーション強調表示に便利です。
import { Router } from "@angular/router";
export class LoginComponent {
constructor(private router: Router) {}
onLogin() {
this.router.navigate(["/dashboard"]); // navigate after an action
}
}
import { ActivatedRoute } from "@angular/router";
export class UserDetailComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// read :id from the URL (params is an Observable, since it can change)
this.route.params.subscribe(p => this.userId = p["id"]);
// or snapshot for a one-time read:
const id = this.route.snapshot.paramMap.get("id");
}
}
Nested/child routes, route guards (auth), resolvers (pre-fetch data),
query params, and lazy loading of feature routes for code splitting.
Router は Angular をマルチビュー SPA に変え、高速なクライアント側ナビゲーション、URL 駆動の UI、深いリンク可能なページを実現します。
ルート設定、<router-outlet>、routerLink vs プログラマティック Router.navigate、および ActivatedRoute 経由のパラメータ読み取りの知識は、任意の Angular アプリケーションの日常的なルーティングニーズをカバーしており、ガードと遅延読み込みがこの基盤の上に構築されます。