Help Angular by taking a 1 minute survey!Go to surveyHome

KeyValuePipe

Transforms Object or Map into an array of key value pairs.

See more...

{{ input_expression | keyvalue [ : compareFn ] }}
      
      {{ input_expression | keyvalue [ : compareFn ] }}
    

NgModule

Input value

input any

Parameters

compareFn (a: KeyValue, b: KeyValue) => number

Optional. Default is defaultComparator.

Description

The output array will be ordered by keys. By default the comparator will be by Unicode point value. You can optionally pass a compareFn if your keys are complex types.

Usage notes

Examples

This examples show how an Object or a Map can be iterated by ngFor with the use of this keyvalue pipe.

@Component({ selector: 'keyvalue-pipe', template: `<span> <p>Object</p> <div *ngFor="let item of object | keyvalue"> {{item.key}}:{{item.value}} </div> <p>Map</p> <div *ngFor="let item of map | keyvalue"> {{item.key}}:{{item.value}} </div> </span>` }) export class KeyValuePipeComponent { object: {[key: number]: string} = {2: 'foo', 1: 'bar'}; map = new Map([[2, 'foo'], [1, 'bar']]); }
      
      
  1. @Component({
  2. selector: 'keyvalue-pipe',
  3. template: `<span>
  4. <p>Object</p>
  5. <div *ngFor="let item of object | keyvalue">
  6. {{item.key}}:{{item.value}}
  7. </div>
  8. <p>Map</p>
  9. <div *ngFor="let item of map | keyvalue">
  10. {{item.key}}:{{item.value}}
  11. </div>
  12. </span>`
  13. })
  14. export class KeyValuePipeComponent {
  15. object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
  16. map = new Map([[2, 'foo'], [1, 'bar']]);
  17. }