1

I am trying to view JavaScript Map type in Angular template and value is coming empty always even when I intialise it with some default value.

Angular Component

export class AppComponent implements OnInit {

  public myJsMap:Map<string,string> = new Map<string,string>([['hello','hello']]);

  ngOnInit(): void {
    this.myJsMap.set('Hello2', 'hellow2')
  }
}

Angular Template

    My Template Value : {{myJsMap | json}}

Tried to console log Map value on the component and it prints correctly on component side but when tried to view same value on template side it is showing empty object always. Anything we need to do on template side to view this value?

Result is empty Object on browser: enter image description here

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
LilRazi
  • 690
  • 12
  • 33
  • Does this answer your question? [How to iterate using ngFor loop Map containing key as string and values as map iteration](https://stackoverflow.com/questions/48187362/how-to-iterate-using-ngfor-loop-map-containing-key-as-string-and-values-as-map-i) – Heretic Monkey Jul 21 '23 at 18:52

2 Answers2

3

You cannot use Angular json pipe against an ES6 Map.

If you check json pipe source, you will find that it makes use of JSON.stringify() method, which results for {} for any ES6 Map

export class JsonPipe implements PipeTransform {
  transform(value: any): string {
    return JSON.stringify(value, null, 2);
  }
}

You can either iterate over your map entries in your component HTML file using NgFor directive and keyvalue pipe like below

<ng-container *ngFor="let entry of myJsMap | keyvalue">
  {{entry.key}} : {{entry.value}}
</ng-container>

OR build your own pipe that can transform it

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

@Pipe({
  name: 'map2json',
})
export class MapToJSONPipe implements PipeTransform {
  transform(map: Map<any, any>): string {
    return JSON.stringify(Array.from(map));  //Or however you want to transform it
  }
}

and use it in your component HTML file like below

{{ myJsMap | map2json }}
fujy
  • 5,168
  • 5
  • 31
  • 50
0
import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
})
export class AppComponent {

    myJsMap = new Map<string,string>([['hello','hello']]);

    ngOnInit(): void {
        this.myJsMap.set('Hello2', 'hellow2')
    }

}

<h1>My Map</h1>

<div>{{myJsMap | toJSON}}</div>
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 25 '23 at 12:57