Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over Map using ngFor and display them in order on html in Angular 2+?

I am using Angular 7.x.

I have implemented the code where using *ngFor, it iterates over Map and display them on html

      <mat-list-item *ngFor="let data of map | keyvalue">
          <div class="col-md-2">
              <p mat-line> {{data.value.name}} </p>           
          </div>            
      </mat-list-item>

It successfully shows a list but problem is it does not show them in order.

For example, if I add A and B to Map, it shows as

A B

However if I add another one, C, then it shows as

A C B

I want it to be as A B C, which is the order I inserted to Map.

If I console.log, then it shows as in order of I inserted but not on html.

I HAVE TO use MAP but I do not know how.

Please help me and thank you in advance.

like image 928
Staytrippy Avatar asked Aug 31 '25 00:08

Staytrippy


1 Answers

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

One solution is to do the following:

Add this method in your TS:

asIsOrder(a, b) {
   return 1;
}

Change your keyvalue pipe to keyvalue: asIsOrder in your HTML:

<mat-list-item *ngFor="let data of map | keyvalue: asIsOrder">
    <div class="col-md-2">
        <p mat-line> {{data.value.name}} </p>           
    </div>            
</mat-list-item>

Source: https://github.com/angular/angular/issues/31420

like image 58
Emerica Avatar answered Sep 02 '25 13:09

Emerica