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

Angular 5中如何使用ngFor迭代嵌套Map?

解决Angular 5中嵌套Map的迭代问题

没问题,我来帮你搞定这个嵌套Map的遍历需求!Angular的*ngFor指令默认更适配数组类型,而Map是键值对集合,所以我们需要先把它转换成数组形式才能顺利遍历,尤其是嵌套的Map,得一层一层来处理。

步骤1:调整组件代码(可选但更清晰)

你可以在组件里定义一个getter方法,把外层Map转换成键值对数组,这样模板里用起来更直观:

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.map.set("yoyoy",this.map1);
 }

 // 新增getter,返回外层Map的键值对数组
 get outerMapEntries() {
   return Array.from(this.map.entries());
 }
}

步骤2:修改模板HTML实现嵌套遍历

现在我们可以在模板里先遍历外层的键值对,再对每个外层值对应的内层Map做同样的转换和遍历:

<ul>
  <!-- 遍历外层Map的键值对,每个entry是 [外层key, 内层Map] -->
  <li *ngFor="let outerEntry of outerMapEntries">
    <strong>{{ outerEntry[0] }}</strong> <!-- 显示外层的key -->
    <!-- 遍历内层Map的键值对 -->
    <ul>
      <li *ngFor="let innerEntry of Array.from(outerEntry[1].entries())">
        键: {{ innerEntry[0] }}, 值: {{ innerEntry[1] }}
      </li>
    </ul>
  </li>
</ul>
<div>外层Map的大小: {{ map.size }}</div>

为什么原来的代码只能显示外层key?

你之前用map.keys()只能拿到外层Map的键的迭代器,*ngFor可以遍历它,但只能获取到外层的key,没办法同时拿到对应的内层Map。而Map.entries()会返回包含键和值的迭代器,转换成数组后就能同时获取到外层key和对应的内层Map,进而实现嵌套遍历。

如果不想在组件里加getter,也可以直接在模板里写Array.from(map.entries()),比如:

<li *ngFor="let outerEntry of Array.from(map.entries())">

效果是一样的,只是组件里加getter会让模板更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:50:16