首页 > 解决方案 > 如何使用角度 11 在 for 循环中使用数组对象?

问题描述

我从后端 API 获取数据,需要在前端循环数据但其值不返回。

这是我来自后端 API 的回复。

[
    [
        {
            "choice": 1,
            "count": 4,
            "percentageValue": "80.0000"
        },
        {
            "choice": 2,
            "count": 1,
            "percentageValue": "20.0000"
        }
    ],
    [
        {
            "choice": 1,
            "count": 4,
            "percentageValue": "80.0000"
        },
        {
            "choice": 2,
            "count": 1,
            "percentageValue": "20.0000"
        }
    ]
]

在 ts 文件中

submitPoll(data){
    this.pollService.submitPoll(data).subscribe(response =>{
      this.percentage=response.body;
    });
  }

在 html 文件中

<p *ngFor="let percentage of percentage;let i= index;">
                  {{percentage.choice  }}
                </p>

如何为数组对象使用 for 循环?我需要在选项中显示百分比

标签: angular

解决方案


正如@MichaelD 提到的,percentage是数组数组。一个简单的解决方案是使用*ngFor两次。

<div *ngFor="let innerArray of percentage;">
  <p *ngFor="let obj of innerArray;">
    {{obj.choice}}
  </p>
</div>

推荐阅读