KeyValue pipe in Angular 6.1

Keyvalue pipe in angular

Note – You can find the source code of my sample application here. You can find all .Net core posts here.

Angular 6.1 is recently announced with some interesting features.

One of those features is, the key value pipe.

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

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

This can be achieved using keyvalue pipe.

What can be achieved using keyvalue pipe?

A pipe to object Map or object (dictionary) to a key value pair array for use in an ngFor

Example

Let us see how it works

Let us 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, array and Map to test the keyvalue pipe.

Next step is to add the html in which we will use keyvalue pipe:

keyval2

Code can be copied from here: https://github.com/NeelBhatt/KeyValuePipeAngular6_1/blob/master/src/src/app/app.component.html

This will result in:

keyval

As you can see above, the syntax is quite easy to iterate objects, array, maps etc using *ngfor.

Note that:

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

Want to see how it works internally, have a look at this commit here:

https://github.com/angular/angular/commit/2b49bf7

Hope it helps.

Note – You can find the source code of my sample application here. You can find all .Net core posts here.

 

2 thoughts on “KeyValue pipe in Angular 6.1

Leave a comment