Angular KeyValue Pipe

The KeyValue Pipe converts given Object or Map into an array of key-value pairs. We can use this with the ngFor to loop through the object keys. The keyValue accepts the one argument compareFn, which we can use to set the custom sort to the pipe. In this tutorial, let us learn how to make use of KeyValue pipe with example.

How it works

Consider, that you have the following object and a map object. It has property a,b & c. We cannot use ngFor to iterate over it as it requires an array. This is where the KeyValue pipe comes into play. It will convert them to an array of key-value pair

We use keyvalue just like any other pipes in Angular and as shown below

The keyValue converts them and returns in the following format. each property of the object a: 789 is converted to an object with name as key and value as value { key:a, value:789 }. It creates array of such objects and returns it.

Now we can use the ngFor to loop through it and display the content.

Default Sorting

KeyValue pipe uses the key to sort the results array. You can see it from the above example. Even though our object was c,b & a it was sorts it as a,b,c. The keyValue pipe uses the defaultComparator to sort the result. It uses

  1. Ascending Order if the keys are number
  2. Alphabetical Order if keys are strings
  3. if keys are are of different types. then covert them to to their string values and use Alphabetical Order
  4. If key is a either Null or undefined, put then at the end of the sort.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

Custom Sorting

You can customize it by providing a custom sort function (compareFn) as the first argument to the keyValue pipe

The syntax for the compareFn as shown below. It accepts first & second keyValue and must return a number. The number must be a zero if values are equivalent else either a negative number or positive number

The following are three compareFn

KeyValue Pipe Example

Consider the following breeds of dogs. The example sorts the list based on the number of sub breeds. The final code is as shown below.

CompareFn

Template

The output

Reference

  1. KeyValue Pipe API
  2. Async Pipe API
  3. KeyValue Pipe Source Code

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top