KeyValue Pipe in Angular 6.1

DZone 's Guide to

KeyValue Pipe in Angular 6.1

With the upcoming release of Angular 6.1, a developer takes a look at one of the features included, KeyValue Pipes. Read on to learn more!

· Web Dev Zone ·
Free Resource

Note - You can find the source code of my sample application here. You can find all .NET Core posts here.

Angular 6.1 was recently announced, and it comes with some interesting features.

One of those features is, the KeyValue pipe.

Currently, there is not any straight forward way to iterate object keys using ngFor in Angular.

I have seen many StackOverflow questions for this and many workarounds to iterate through objects and arrays in Angular. But now there is a straight and easier way for this.

This can be achieved using the keyvalue pipe.

What can be achieved using keyvalue pipe?

We can create a pipe to an object Map or object (dictionary) to a key value pair array for use in an ngFor.


Let us see how it works.

Let's add a component with objects and array as below:

export class Angular6_1Component {

myValues = { “key1“: “value1“, “key2“: “value2“ };
myObject: {[key: number]: string} = {2: ‘I am two’, 1: ‘I am one’};

myArray = [“I am an array 1”, “I am an array 2”]
myMap = new Map([[2, ‘I am two’], [1, ‘I am one’]]);

As you can see above, I have added different objects, an array and a Map, to test the keyvalue pipe.

The next step is to add in the HTML in which we will use keyvalue pipe:

The ode can be copied from my GitHub repo.

This will result in:

As you can see above, the syntax makes it quite easy to iterate objects, array, maps, etc. using *ngFor.

Note that:

  • As Arrays only have values, keys will start from 0.
  • objects\arrays will arrange the order of the keys.
  • If the keys are string, keys will be arranged in alphabetical order.

If you want to see how it works internally, have a look at this commit here.

Hope this helps!

Note - You can find the source code of my sample application here. You can find all .NET Core posts here.

angular 6, keyvalue, tutorial, web dev

Published at DZone with permission of Neel Bhatt , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}