gpt4 book ai didi

javascript - 如何使用包含键作为字符串和值作为映射迭代的 ngFor 循环映射进行迭代

转载 作者:太空狗 更新时间:2023-10-29 16:46:43 25 4
gpt4 key购买 nike

我是 Angular 5 的新手,正在尝试迭代包含 typescript 中的另一个 map 的 map 。如何以 Angular 在这种 map 下方迭代以下是组件代码:

import { Component, OnInit} from '@angular/core';

@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
map = new Map<String, Map<String,String>>();
map1 = new Map<String, String>();

constructor() {


}

ngOnInit() {
this.map1.set("sss","sss");
this.map1.set("aaa","sss");
this.map1.set("sass","sss");
this.map1.set("xxx","sss");
this.map1.set("ss","sss");


this.map1.forEach((value: string, key: string) => {
console.log(key, value);

});


this.map.set("yoyoy",this.map1);

}



}

它的模板 html 是:

<ul>
<li *ngFor="let recipient of map.keys()">
{{recipient}}
</li>


</ul>

<div>{{map.size}}</div>

runtime error

最佳答案

对于 Angular 6.1+ ,您可以使用默认管道 keyvalue ( Do review and upvote also ) :

<ul>
<li *ngFor="let recipient of map | keyvalue">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>

WORKING DEMO


对于之前的版本:

一个简单的解决方案是将映射转换为数组: Array.from

组件端:

map = new Map<String, String>();

constructor(){
this.map.set("sss","sss");
this.map.set("aaa","sss");
this.map.set("sass","sss");
this.map.set("xxx","sss");
this.map.set("ss","sss");
this.map.forEach((value: string, key: string) => {
console.log(key, value);
});
}

getKeys(map){
return Array.from(map.keys());
}

模板端:

<ul>
<li *ngFor="let recipient of getKeys(map)">
{{recipient}}
</li>
</ul>

WORKING DEMO

关于javascript - 如何使用包含键作为字符串和值作为映射迭代的 ngFor 循环映射进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com