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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48187362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:02:41  来源:igfitidea点击:

How to iterate using ngFor loop Map containing key as string and values as map iteration

javascriptangulartypescriptangular-cli

提问by Feroz Siddiqui

I am new to angular 5 and trying to iterate the map containing another map in typescript. How to iterate below this kind of map in angular below is code for component:

我是 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);

  }



}

and its template html is :

它的模板html是:

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


</ul>

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

runtime error

运行时错误

回答by Vivek Doshi

For Angular 6.1+, you can use default pipe keyvalue( Do review and upvote also) :

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

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

WORKING DEMO

工作演示



For the previous version :

对于以前的版本:

One simple solution to this is convert map to array : Array.from

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

Component Side :

组件端:

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());
}

Template Side :

模板端:

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

WORKING DEMO

工作演示

回答by Londeren

If you are using Angular 6.1 or later, the most convenient way is to use KeyValuePipe

如果您使用的是 Angular 6.1 或更高版本,最方便的方法是使用KeyValuePipe

   @Component({
      selector: 'keyvalue-pipe',
      template: `<span>
        <p>Object</p>
        <div *ngFor="let item of object | keyvalue">
          {{item.key}}:{{item.value}}
        </div>
        <p>Map</p>
        <div *ngFor="let item of map | keyvalue">
          {{item.key}}:{{item.value}}
        </div>
      </span>`
    })
    export class KeyValuePipeComponent {
      object: Record<number, string> = {2: 'foo', 1: 'bar'};
      map = new Map([[2, 'foo'], [1, 'bar']]);
    }

回答by David

Edit

编辑

For angular 6.1 and newer, use the KeyValuePipeas suggested by Londeren.

对于Angular 6.1 和更新版本,请使用Londeren 建议的KeyValuePipe

For angular 6.0 and older

对于 Angular 6.0 及更早版本

To make things easier, you can create a pipe.

为了使事情更容易,您可以创建一个管道。

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

@Pipe({name: 'getValues'})
export class GetValuesPipe implements PipeTransform {
    transform(map: Map<any, any>): any[] {
        let ret = [];

        map.forEach((val, key) => {
            ret.push({
                key: key,
                val: val
            });
        });

        return ret;
    }
}

 <li *ngFor="let recipient of map |getValues">

As it it pure, it will not be triggered on every change detection, but only if the reference to the mapvariable changes

就其纯粹而言,它不会在每次更改检测时触发,只有在对map变量的引用发生更改时才会触发

Stackblitz demo

Stackblitz 演示

回答by Armen Vardanyan

This is because map.keys()returns an iterator. *ngForcan work with iterators, but the map.keys()will be called on every change detection cycle, thus producing a new reference to the array, resulting in the error you see. By the way, this is not always an erroras you would traditionally think of it; it may even not break any of your functionality, but suggests that you have a data model which seems to behave in an insane way - changing faster than the change detector checks its value.

这是因为map.keys()返回一个迭代器。*ngFor可以与迭代器一起工作,但map.keys()将在每个更改检测周期中调用,从而产生对数组的新引用,从而导致您看到的错误。顺便说一句,这并不总是像您传统上认为的那样错误;它甚至可能不会破坏您的任何功能,但表明您的数据模型似乎以一种疯狂的方式运行——变化速度比变化检测器检查其值的速度快。

If you do no want to convert the map to an array in your component, you may use the pipe suggested in the comments. There is no other workaround, as it seems.

如果您不想将地图转换为组件中的数组,您可以使用注释中建议的管道。似乎没有其他解决方法。

P.S. This error will not be shown in the production mode, as it is more like a very strict warning, rather than an actual error, but still, this is not a good idea to leave it be.

PS 这个错误不会在生产模式中显示,因为它更像是一个非常严格的警告,而不是一个实际的错误,但仍然不是一个好主意。