49

KeyValue pipe in Angular 6.1

 4 years ago
source link: https://www.tuicool.com/articles/hit/ryeqiej
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

iEBFNfE.png!web

Angular 6.1is 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:

My Values:

Key: {{item.key}} and Value: {{item.value}}

My Object:

Key: {{item.key}} and Value: {{item.value}}

My Array:

Key: {{item.key}} and Value: {{item.value}}

My Map:

Key: {{item.key}} and Value: {{item.value}}

This will result in:

Mja6Bjf.png!web

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK