Angular KeyValue Pipe Example

Angular KeyValue Pipe Example

Angular KeyValuePipe is used to iterate over Object or Map. Angular KeyValuePipe transforms the Object or Map into an array of key-value pair.

Angular KeyValuePipe was introduced in Angular Version 6.1. so if you’re using the version before 6.1, you won’t be able to use KeyValuePipe. You’ll have to update your angular version.

Prior to Angular version 6.1 ngFor directive doesn’t have support to iterate over Object or Map, to handle this issue KeyValuePipe was introduced.

Syntax

{{ input_expression | keyvalue [ : compareFn ] }}

Input

input is Object or Map.
i.e  
object: {[key: number]: string} = {2: ‘foo’, 1: ‘bar’};
or
map = new Map([[2, ‘foo’], [1, ‘bar’]]);

compareFn

compareFn is optional. Default it defaultComparator. and the output array will be ordered by keys. You can pass optional custom comparer if you’ve complex keys.


Example

1. KeyValuePipe with Object

app.component.ts
Here in the component file, we’ll define a simple object and that it will be used to show it’s key and values using KeyValuePipe


import { Component } from '@angular/core';
import { FormControl, FormGroup } from "@angular/forms";
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
}

app.component.html
In the template file, we’ll use KeyValuePipe as following and will display the Object’s keys and values.


<span>
    <p>Object's keys and values are as following:</p>
    <div *ngFor="let item of object | keyvalue">
      Key:{{item.key}} and Value:{{item.value}}
    </div>
  </span> 

Output

As you can see in the above output that the output array will be ordered by keys even if the input object has the first key name with 2.

Here we can also use the JsonPipe to see how KeyValuePipe generates key-value pair as following.


<span>
    <p>Object's keys and values are as following:</p>
    <div *ngFor="let item of object | keyvalue">
      {{item | json}}<br/>
      Key:{{item.key}} and Value:{{item.value}}
      <br/><br/>
    </div>
  </span>

Output

To know more about JsonPipe, you can read this article Angular Json Pipe Example for Debugging


2. KeyValuePipe with Map

app.component.ts
Here in the component file, We’ll define a simple Map and that it will be used to show it’s key and values using KeyValuePipe.


import { Component } from '@angular/core';
import { FormControl, FormGroup } from "@angular/forms";
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  map = new Map([[2, 'foo'], [1, 'bar']]);
}

app.component.html
In the template file, We’ll use KeyValuePipe as following and will display Map’s keys and values.


<span>
    <p>Map's keys and values are as following :</p>
    <div *ngFor="let item of map | keyvalue">
      Key:{{item.key}} and Value:{{item.value}}
    </div>
  </span>

Output


3. Object with keys are numbers – Default Sorting

If the keys are numbers, the output array will be sorted by ascending order as the following example.

Here in this example, we’ll see how the output array will be sorted using default sorting (default compareFn) when the object with keys are numbers is supplied as input.

app.component.ts


import { Component } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  object: { [key: number]: string } = {
    3: "Test 3",
    4: "Test 4",
    2: "Test 2",
    1: "Test 1"
  };
}

app.component.html


<span>
    <p>Object with keys are mixed:</p>
    <div *ngFor="let item of object | keyvalue">
      Key:{{item.key}} and Value:{{item.value}}
    </div>
  </span>

Output

4. Object with keys are string – Default Sorting

If the keys are string, the output array will be sorted by alphabetical order as the following example.

Here in this example, we’ll see how the output array will be sorted using default sorting (default compareFn) when the object with keys are string is supplied as input.

app.component.ts


import { Component } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  object: { [key: string]: string } = {
    'zzz': "Test 3",
    'aaa': "Test 4",
    'ccc': "Test 2",
    'fff': "Test 1"
  };
}

app.component.html


<span>
    <p>Object with keys are string:</p>
    <div *ngFor="let item of object | keyvalue">
      Key:{{item.key}} and Value:{{item.value}}
    </div>
  </span>

Output

5. Object with keys are mixed – Default Sorting

If the keys are mixed or if the keys are number as well as string, the output array will be first sorted by ascending order and then by alphabetical order as the following example.

Here in this example, we’ll see how the output array will be sorted using default sorting (default compareFn) when the object with keys are mixed is supplied as input.

app.component.ts


import { Component } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
   object: { [key: string]: string } = {
    'zzz': "Test 3",
    'aaa': "Test 4",
    'ccc': "Test 2",
    'fff': "Test 1",
    3: "Test 3",
    4: "Test 4",
    2: "Test 2",
    1: "Test 1"
  };
}

app.component.html


<span>
    <p>Object with keys are mixed:</p>
    <div *ngFor="let item of object | keyvalue">
      Key:{{item.key}} and Value:{{item.value}}
    </div>
  </span>

Output

6. Custom Comparer Function For Descending Order

As we already know that the KeyValuePipe is using defaultComparator as compareFn which sort by ascending or alphabetical order depending on the keys.

Sometimes we might not need to sort it by default behaviour but we might want to show it in the descending order. In that case, we can create comparer function and pass it to KeyValuePipe.

app.component.ts


import { Component } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
import { KeyValue } from '@angular/common'
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  object: { [key: number]: string } = {
    3: "Test 3",
    4: "Test 4",
    2: "Test 2",
    1: "Test 1"
  };
keyDescOrder = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {
  return a.key > b.key ? -1 : (b.key > a.key ? 1 : 0);
  }
}

Here in the above code, we’ve created keyDescOrder comparer function, which will sort by descending order.

app.component.html


<span>
    <p>Object with keys are mixed:</p>
    <div *ngFor="let item of object | keyvalue : keyDescOrder">
      Key:{{item.key}} and Value:{{item.value}}
    </div>
  </span>

Output

I think that’s pretty much it for KeyValuePipe.

Leave a Comment