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

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


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

<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

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


If you are using Angular 6.1 or later, the most convenient way is to use 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']]);    }


Edit

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

For angular 6.0 and older

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 map variable changes

Stackblitz demo