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

标签 javascript angular typescript angular-cli

我是 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/

相关文章:

json - 来自导入文件而非数据库的 Google map 坐标

javascript - 格式化javascript日期以匹配rails格式

javascript - Angular 4 Bootstrap 下拉菜单需要 Popper.js

angular - Datalayer.push 在 Angular 6 中使用 Typescript

javascript - Angular 5 Material Multiple mat-menu

Angular 2 : *ngFor does not update when array is updated

intellij-idea - 如何在 IntelliJ IDEA 中为 TypeScript 自定义分号帮助

javascript - jquery中 `$(undefined)`的返回值是多少

javascript - pdfmake base64 图片回调

javascript - 合并 2 个 javascript/jquery 随机横幅图像/文本函数相互对应?