【Angular】KeyValuePipe の使い方
概要
Angular 6.1.0になりKeyValuePipe
が追加されました。
KeyValuePipe
のサンプルを作ってみたいと思います。
以下はAngular 6.1をピックアップした記事です。
kakkoyakakko2.hatenablog.com
動作環境
- Node.js 8.x
- TypeScript 2.9.x
- Angular 6.1.x
サンプルソース一式
以下のGithubのソースコード一式をダウンロードしてnpm install
、npm start
をすればサンプルの実行ができます。
github.com
KeyValuePipeとは
サンプルソース
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <!-- 連想配列 --> <h3>keyValues loop</h3> <ul> <li *ngFor="let pair of keyValues | keyvalue"> {{ pair.key }}: {{ pair.value }} </li> </ul> <!-- Map --> <h3>map loop</h3> <ul> <li *ngFor="let pair of map | keyvalue"> {{ pair.key }}: {{ pair.value }} </li> </ul> ` }) export class AppComponent { /** Associative array */ keyValues = { key1: 'value1', key2: 'value2', key3: 'value3', }; /** Map */ map = new Map<string, string>([ ['mapKey1', 'mapValue1'], ['mapKey2', 'mapValue2'], ['mapKey3', 'mapValue3'], ]); }
実行結果
その他
以下のケースで使用できるかと思います。
- keyが表示項目として使用したい場合
- コンボボックスのデータ
keyを表示項目、valueを値として利用