When using the Angular keyvalue pipe to iterate over an object's properties as follows:
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
I have experienced an issue where the properties were not iterated in the order expected. And this comment suggests that I am not the only one to experience this issue:
How to loop over object properties with ngFor in Angular
Can someone advise what determines the order of iteration when using the keyvalue pipe please and how to force a specific iteration order? My ideal order of iteration is the order in which the properties were added.
Thanks
This is same as accepted answer, but it has more complex object so It can help somebody How to sort by custom index field and using keyval pipe.
In angular component:
Sorting function in component:
in template:
According to the Angular documentation, the
keyvalue
pipe sorts the items bykey
order by default. You can provide a comparer function to change the sort order, but it only considers thekey
andvalue
properties, not the entry order.For example, the following comparer functions sort the items by increasing value order, and by reverse key order, respectively:
when applied to the
keyvalue
pipe:See this stackblitz for a demo.
Yes,
Object
properties iterates randomly since it doesn't get stored asarray
in memory. However you can sort by properties.If you want to iterate by insertion position, you need to create one extra property like
index
and set thetimestamp
and sort byindex
.Below is the pipe you can use to control the sorting and iteration
Pipe
Usage