Locationサービスを使ってURL内のパラメータをrouterLinkに渡す
AngularでURL内のパラメータをrouterLinkに渡す方法
クエリパラメータを使用する
最も一般的な方法は、クエリパラメータを使用する方法です。クエリパラメータは、URLの末尾に ?
記号とパラメータ名と値のペアが続く形式で指定されます。
例:
/home?id=123
この場合、id
という名前のパラメータがあり、その値は 123
です。
クエリパラメータをrouterLinkに渡すには、以下の方法があります。
- routerLinkディレクティブのqueryParamsプロパティを使用する
<a [routerLink]="['/detail', {queryParams: {id: 123}}]">詳細</a>
このコードは、/detail
というパスにルーティングし、id
という名前のクエリパラメータに 123
という値を渡します。
<a [routerLink]="'/detail?id=123'">詳細</a>
このコードは、/detail?id=123
というURLに直接ルーティングします。
パスパラメータを使用する
パスパラメータは、URLのパスの部分に埋め込まれたパラメータです。
/detail/123
この場合、123
というパスパラメータがあり、これは詳細ページのIDを表します。
パスパラメータをrouterLinkに渡すには、以下の方法があります。
<a [routerLink]="['/detail', 123]">詳細</a>
<a [routerLink]="'/detail/123'">詳細</a>
上記以外にも、以下の方法でURL内のパラメータをrouterLinkに渡すことができます。
- Fragment identifierを使用する
- routerState.snapshot.paramsを使用する
- Custom routerLink directiveを使用する
詳細は、Angularの公式ドキュメントを参照してください。
<a [routerLink]="['/detail', {queryParams: {id: 123}}]">詳細</a>
<a [routerLink]="['/detail', 123]">詳細</a>
<a [routerLink]="['/detail', {fragment: 'section-1'}]">詳細</a>
<a [routerLink]="['/detail', routerState.snapshot.params['id']]">詳細</a>
<a [customRouterLink]="['/detail', id]">詳細</a>
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
id: number;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.id = this.route.snapshot.params['id'];
}
}
このコードは、以下のことを行います。
/detail
というパスにルーティングするリンクを作成します。- クエリパラメータ、パスパラメータ、Fragment identifier、routerState.snapshot.params、Custom routerLink directiveを使用して、URL内のパラメータをrouterLinkに渡します。
このコードを参考に、ご自身のアプリケーションでURL内のパラメータをrouterLinkに渡すようにしてください。
URL内のパラメータをrouterLinkに渡す他の方法
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class MyService {
constructor(private router: Router) {}
navigateToDetail(id: number) {
this.router.navigate(['/detail', id]);
}
}
<a (click)="myService.navigateToDetail(123)">詳細</a>
MyService
というサービスを作成します。navigateToDetail
というメソッドを作成し、このメソッドはid
というパラメータを受け取ります。router.navigate
メソッドを使用して、/detail
というパスにルーティングします。
<a [routerLink]="['/detail', encodeURIComponent(id)]">詳細</a>
このコードは、id
というパラメータをURLエンコードし、/detail
というパスにルーティングします。
import { Injectable } from '@angular/core';
import { Location } from '@angular/common';
@Injectable()
export class MyService {
constructor(private location: Location) {}
navigateToDetail(id: number) {
this.location.go('/detail/' + id);
}
}
<a (click)="myService.navigateToDetail(123)">詳細</a>
URL内のパラメータをrouterLinkに渡す方法はいくつかあります。ご自身のアプリケーションに合った方法を選択してください。
angular angular2-routing angular2-router3