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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With