You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular模板中JavaScript Map类型值无法显示的问题

问题

在Angular模板中尝试展示JavaScript Map类型数据,即便初始化了默认值,模板里始终显示为空对象。组件内通过console.log能正常打印Map的内容,但模板中无法正确渲染。

组件代码

export class AppComponent implements OnInit {

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

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

模板代码

My Template Value : {{myJsMap | json}}
解决方案

Angular内置的json管道无法序列化JavaScript的Map类型(因为Map不属于JSON标准支持的数据结构),所以会被转换为空对象{}。可以通过以下几种方式解决:

  • 方法1:自定义转换管道
    创建一个自定义管道,将Map转换为普通对象后再用json管道处理:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ name: 'mapToObject' })
    export class MapToObjectPipe implements PipeTransform {
      transform(map: Map<any, any>): object {
        return Object.fromEntries(map.entries());
      }
    }
    

    在模板中使用:

    My Template Value : {{myJsMap | mapToObject | json}}
    

    注意需要在对应模块的declarations数组中声明该管道。

  • 方法2:组件内维护同步的普通对象
    在组件中创建一个与Map同步的普通对象,模板直接绑定这个对象:

    export class AppComponent implements OnInit {
      public myJsMap: Map<string, string> = new Map<string, string>([['hello','hello']]);
      public myMapObj: { [key: string]: string } = {};
    
      ngOnInit(): void {
        this.syncMapToObject();
        this.myJsMap.set('Hello2', 'hellow2');
        this.syncMapToObject();
      }
    
      private syncMapToObject(): void {
        this.myMapObj = Object.fromEntries(this.myJsMap.entries());
      }
    }
    

    模板中使用:

    My Template Value : {{myMapObj | json}}
    
  • 方法3:模板内直接转换(不推荐)
    可以在模板中直接调用Object.fromEntries转换,但频繁的变更检测会影响性能。需要先在组件中暴露Object:

    export class AppComponent implements OnInit {
      public Object = Object;
      public myJsMap: Map<string, string> = new Map<string, string>([['hello','hello']]);
    
      ngOnInit(): void {
        this.myJsMap.set('Hello2', 'hellow2')
      }
    }
    

    模板代码:

    My Template Value : {{Object.fromEntries(myJsMap.entries()) | json}}
    

内容的提问来源于stack exchange,提问作者LilRazi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 18:58:16