Angular array iteration changes the original order value.

 

Angular array iteration changes the original order value.


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

  {{item.key}}:{{item.value}}

</div>

Original array values order changes


So here is solution.

// Preserve original property order

originalOrder = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {

  return 0;

}


// Order by ascending property value

valueAscOrder = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {

  return a.value.localeCompare(b.value);

}


// Order by descending property key

keyDescOrder = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {

  return a.key > b.key ? -1 : (b.key > a.key ? 1 : 0);

}

 Apply key-value pipe with order functionality:


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

  {{item.key}} : {{item.value}}

</div>


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

  {{item.key}} : {{item.value}}

</div>


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

  {{item.key}} : {{item.value}}

</div>


Reference

https://stackoverflow.com/questions/52793944/angular-keyvalue-pipe-sort-properties-iterate-in-order

Share this

Related Posts

Previous
Next Post »