AngularでrouterLinkを使ってクエリパラメータを渡す方法
AngularでrouterLinkを使ってクエリパラメータを渡す方法
queryParams オプションを使う
コンポーネント側
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
})
export class MyComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.navigate(['/other-component'], {
queryParams: {
id: 123,
name: 'John Doe',
},
});
}
}
テンプレート側
<a routerLink="/other-component" [queryParams]="{id: 123, name: 'John Doe'}">
他のコンポーネントへ移動
</a>
上記のように、queryParams
オプションを使ってオブジェクトを渡すことで、クエリパラメータとして情報を追加できます。
routerLink ディレクティブの属性を使う
<a routerLink="/other-component?id=123&name=John Doe">
他のコンポーネントへ移動
</a>
上記のように、routerLink
ディレクティブの属性に直接クエリパラメータを記述することもできます。
URLSearchParamsを使う
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
})
export class MyComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
const params = new URLSearchParams();
params.append('id', '123');
params.append('name', 'John Doe');
this.router.navigate(['/other-component'], {
queryParams: params,
});
}
}
上記のように、URLSearchParams
オブジェクトを使ってクエリパラメータを生成し、それをqueryParams
オプションに渡すこともできます。
クエリパラメータは、文字列、数値、日付など、さまざまな型のデータを渡すことができます。
interface MyQueryParams {
id: number;
name: string;
date: Date;
}
const params: MyQueryParams = {
id: 123,
name: 'John Doe',
date: new Date(),
};
this.router.navigate(['/other-component'], {
queryParams: params,
});
上記のように、インターフェースを使ってクエリパラメータの型を定義することもできます。
まとめ
AngularでrouterLinkを使ってクエリパラメータを渡す方法はいくつかあります。上記の方法を参考に、状況に応じて適切な方法を選択してください。
AngularでrouterLinkを使ってクエリパラメータを渡すサンプルコード
<a routerLink="/other-component" [queryParams]="{id: 123, name: 'John Doe'}">
他のコンポーネントへ移動
</a>
<a routerLink="/other-component?id=123&name=John Doe">
他のコンポーネントへ移動
</a>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
}
}
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'my-other-component',
templateUrl: './other-component.component.html',
styleUrls: ['./other-component.component.css']
})
export class OtherComponent implements OnInit {
id: number;
name: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.id = this.route.snapshot.queryParams['id'];
this.name = this.route.snapshot.queryParams['name'];
}
}
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/other-component', pathMatch: 'full' },
{ path: 'other-component', component: OtherComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
上記は、routerLink
を使ってクエリパラメータを渡すサンプルコードです。
app.component.html
では、2つの方法でクエリパラメータを渡しています。queryParams
オプションを使う方法- URL に直接クエリパラメータを記述する方法
other-component.ts
では、ActivatedRoute
を使ってクエリパラメータを取得しています。app-routing.module.ts
では、ルーティング設定をしています。
このサンプルコードを参考に、実際に試してみてください。
AngularでrouterLinkを使ってクエリパラメータを渡す他の方法
router.navigateByUrl()を使う
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
})
export class MyComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.navigateByUrl('/other-component?id=123&name=John Doe');
}
}
上記のように、router.navigateByUrl()
メソッドを使って、URL を直接指定することでクエリパラメータを渡すこともできます。
Location サービスを使う
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
})
export class MyComponent implements OnInit {
constructor(private location: Location) {}
ngOnInit() {
this.location.go('/other-component?id=123&name=John Doe');
}
}
クエリパラメータエンコーダーを使う
クエリパラメータの中には、特殊文字が含まれている場合があります。そのような場合は、クエリパラメータエンコーダーを使ってエンコードする必要があります。
import { encodeURIComponent } from '@angular/common';
const params = {
id: 123,
name: 'John Doe & Co.',
};
const encodedParams = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
this.router.navigate(['/other-component'], {
queryParams: encodedParams,
});
上記のように、encodeURIComponent
関数を使ってエンコードすることで、特殊文字を含むクエリパラメータを渡すことができます。
angular angular2-routing