【问题标题】:ngFor over nested map in typescriptngFor 在打字稿中的嵌套地图
【发布时间】:2021-01-11 13:50:10
【问题描述】:

我想遍历嵌套映射以从第二个映射的列表中获取值。

地图:

public groupedItemMap: Map<string, Map<string, ItemSearchResult[]>>;

地图结构:

Map
--[[Entries]]
----0
-------key - number (if occured once or is duplicate)
-------value - Map
---------[[Entries]]
-----------key - itemNumber
-----------value - List of object(s) with parameters 'id',..'name' and so on and same itemNumber

++++++++++++if itemNumber is different there are more objects of the same type with different itemNumber
-----------key
-----------value

我想访问其中的对象列表。

  <!-- Here keyvalue is not possible on groupedItemMap -->
<div *ngFor="let group of groupedItemMap.entries()">   
    <span>{{ group.key }}</span>
    <div *ngFor="let items of group| keyvalue">
        <span>{{ items.key }}</span>
        <div *ngFor="let item of items.value">
            <span>{{ item.id }}</span>
        </div>
    </div>
</div>

如果我在 groupedItemMap 上不使用 keyvalue 使用它,我只能使用 4 个 *ngFor 循环和 map.entries() 访问它,这会循环我的 html 标记中的所有项目。

【问题讨论】:

    标签: angular typescript for-loop multidimensional-array hashmap


    【解决方案1】:

    您可能需要对两个循环都使用keyvalue。试试下面的

    <li class="list-group-item" *ngFor="let first of groupedItemMap">
     <div *ngFor="let second of first | keyvalue">
       <div *ngFor="let item of second.value | keyvalue">
         <!-- Here `item.value` is an array. So you possibly need another *ngFor. Test with `json` pipe -->
         <strong innerHTML="{{ item.key }} x {{ item.value | highlight: highlight }}">
         </strong>
         <span class="text-description margin-bottom-5"
             innerHTML="{{ 'number' | translate }}: {{ item.number|highlight:highlight }}"></span>
       </div>
     </div>
    

    【讨论】:

    • 如果我在两个循环中都使用keyvalue,我会得到一个编译器错误。如果我添加另一个循环,即使使用second.value,仍然会出现同样的错误。
    猜你喜欢
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2018-06-25
    • 2018-11-27
    • 2021-06-28
    • 2018-05-06
    相关资源
    最近更新 更多