angulartypescriptangular-pipe

angular keyvalue pipe sort properties / iterate in order


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


Solution

  • The way to keep the items unsorted , as stated many times before here, is indeed:

    <div *ngFor="let item of object | keyvalue: unsorted">
    

    But the function for unsorted should return 1 (always prefer first element; whereas 0 means both elements are equal, and therefore ordering might be implemented differently), and nowadays be protected as well:

    protected readonly unsorted = () => 1;