1

I am using ngFor to display a Map. To do so, I am using the keyvalue. It looks like this:

*ngFor="let upgrade of upgrades | keyvalue"

My Problem now is, that keyvalue sorts my Map. I don't want this and don't know how to stop the sorting.

I tried using sortOrder = (a): number => {return (a)}; as compareFn; it worked, but I don't think that this is the corret way of doing it?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
foo.doo
  • 63
  • 1
  • 11
  • 1
    This might be sidetracking, but, what is wrong with actually sorting the info? Usually that makes it nicer for the end user's view :) – Alejandro Vales Mar 08 '19 at 22:17

2 Answers2

0

since you are working with Map, If you do not want to sort the key you can use

*ngFor="let key of upgrades.keys()"

or

 *ngFor="let entry of upgrades.entries()"

if you still want to use keyvalue pipe, your way is the right way. although it's a little confusing. Since compareFn return a number, your sortOrder function will probably understand as null or NaN. I prefer (a,b)=>1 to be more clear. But it does not matter, the sorting is still happening, and probably waste some CPU time.

Haijin
  • 2,561
  • 2
  • 17
  • 30
  • I did actually see that attempt here: [link](https://stackoverflow.com/questions/48187362/how-to-iterate-using-ngfor-loop-map-containing-key-as-string-and-values-as-map-i). But, as mentioned there, this doesn't work. – foo.doo Mar 09 '19 at 01:11
  • Surprised to see that does not work, but good to know. Thanks. – Haijin Mar 09 '19 at 02:34
0

Yes, the keyvalue pipe does sort by the keys. I suspect this was a requirement for ngClass and ngStyle, because this was mentioned in the source code comments.

You can't stop the sorting. I'd just create my own pipe.

@Pipe({name: 'entries', pure: true})
export class EntriesPipe implements PipeTransform {
     transform(value: May<any,any>) {
         return Array.from(value.entries());
     }
}

I made the pipe pure, but that's up to you. It's difficult to work with Map<> types if it's pure.

Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • Sidenote: although this will work, you will lose some of the optimizations that the keyvalue pipe has https://github.com/angular/angular/blob/7.2.8/packages/common/src/pipes/keyvalue_pipe.ts#L25-L88 – Jota.Toledo Mar 09 '19 at 08:19