在角度4模板中显示地图内容 [英] display map content in angular 4 template
问题描述
我正在尝试在模板中显示地图:
I'm trying to display a map in my template :
myMap : Map<string, Array<ATypeOfMine>>
尝试使用
<div *ngFor="let myStuff of myMap.entries()">
...
</div>
我收到一条错误消息,告诉我除了数组之外我不能迭代其他任何东西.而且我找不到任何方式来获取我的条目并进行处理
I'm getting an error telling I can't iterate over anything but an Array. And I can't find any way to get my entries and work on them
有什么主意吗?
推荐答案
Angular有一个名为"KeyValuePipe"的给定管道.
Angular has a given pipe called "KeyValuePipe".
<div *ngFor="let mapEntry of myMap | keyvalue"></div>
KeyValuePipe返回带有Angular的KeyValue形状的模型.因此,要访问您的字符串键,您需要进行链接:
The KeyValuePipe returns a model w/ Angular's KeyValue shape. So to access your string key, you'd chain:
mapEntry.key
要访问ATypeOfMine数组值,请进行链接:
To access your ATypeOfMine array values, you'd chain:
mapEntry.value.____etc
KeyValuePipe的默认顺序将按Unicode排序.如果要按插入顺序对它们进行排序,则必须向地图管道传递一个compareFn,并为每个值添加一个索引属性.
The default order the KeyValuePipe will be sorted by unicode. If you wanted to sort them by insertion order, you'd have to pass the map pipe a compareFn, and add an index property per value.
我用这个:
(akv: KeyValue<number, any>, bkv: KeyValue<number, any>): number => {
const a = akv.value.index;
const b = bkv.value.index;
return a > b ? 1 : (b > a ? -1 : 0);
}
*我从另一个堆栈溢出线程中找到了上面的比较fn.
* I found the above compare fn from another stack overflow thread.
这篇关于在角度4模板中显示地图内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!