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

新手上路,请多包涵

我是 angular 5 的新手,并试图在打字稿中迭代包含另一个地图的地图。如何在下面的角度迭代这种地图是组件的代码:

 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>

运行时错误

原文由 Feroz Siddiqui 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 634
2 个回答

对于 Angular 6.1+ ,您可以使用默认管道 keyvalue也进行审查和 投票):

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

工作演示


对于以前的版本:

一个简单的解决方案是将映射转换为数组: 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>

工作演示

原文由 Vivek Doshi 发布,翻译遵循 CC BY-SA 4.0 许可协议

Angular的 keyvalue 管道可以用,可惜是按键排序的。地图已经有订单了,如果能保留就太好了!

我们可以定义自己的管道 mapkeyvalue 保留地图中项目的顺序:

 import { Pipe, PipeTransform } from '@angular/core';

// Holds a weak reference to its key (here a map), so if it is no longer referenced its value can be garbage collected.
const cache = new WeakMap<ReadonlyMap<any, any>, Array<{ key: any; value: any }>>();

@Pipe({ name: 'mapkeyvalue', pure: true })
export class MapKeyValuePipe implements PipeTransform {
  transform<K, V>(input: ReadonlyMap<K, V>): Iterable<{ key: K; value: V }> {
    const existing = cache.get(input);
    if (existing !== undefined) {
      return existing;
    }

    const iterable = Array.from(input, ([key, value]) => ({ key, value }));
    cache.set(input, iterable);
    return iterable;
  }
}

它可以像这样使用:

 <mat-select>
  <mat-option *ngFor="let choice of choicesMap | mapkeyvalue" [value]="choice.key">
    {{ choice.value }}
  </mat-option>
</mat-select>

原文由 Patrick Smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题