skip to Main Content

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

2

Answers


  1. 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 }}
    
    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search