Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngFor using a Map

I'm using ionic 3, thus angular and typescript.

What I'm trying to achieve is to use the ngFor with a Map type.

Here is what I have:

interface IShared_Position {
lat: number;
lng: number;
time: number;
color?: string;
}
public shared_position = new Map<string, IShared_Position>();

And now from the html side I have:

    <ion-list>
  <ion-item ion-item *ngFor="let item of shared_position">
    <h2>{{ item.time }}</h2>
  </ion-item>

Now this gives me the following error:

Error: Cannot find a differ supporting object '[object Map]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Now is there any possibile way I cant bind my map even if it is not iterable?

What should I do?

like image 674
Zeno Trevisan Avatar asked May 03 '18 13:05

Zeno Trevisan


Video Answer


1 Answers

if you only need the values, you can iterate over those

html:

<ion-item ion-item *ngFor="let item of getValues()">
    <h2>{{ item.time }}</h2>
</ion-item>

ts:

getValues(): Array<IShared_Position> {
    return Array.from(this.shared_position.values());
}

if you need both values, you can convert the Map to an iterateable object containing arrays with the key at index 0 and value at index 1 using the entries-function:

html:

<ion-item ion-item *ngFor="let item of getEntries()">
    <h2>key: {{ item[0] }} - time: {{item[1].time}}</h2>
</ion-item>

ts:

getEntries(): [string, IShared_Position] {
    return Array.from(this.shared_position.entries());
}
like image 164
Leon Avatar answered Oct 03 '22 13:10

Leon