首页 > 解决方案 > ngfor 用于具有 ng2-charts 的对象中的数组

问题描述

我正在尝试使用 ng2-charts 绘制许多图表。我ngFor用来在我的数组中循环并制作与我的数组一样多的情节。

其实我有一个这样的数组:

   full_graph =  [
    {
    data : [2,4],
    labels: ['oct','nov']
    },
    {
    data : [2,4],
    labels: ['oct','nov']
    }
    ]

所以我应该有 2 个图表(实际上是折线图)。

在我的 html 文件中:

  <ion-list *ngFor="let data of full_graph">
    <ion-card *ngFor= 'let d of data'>
        {{d.data}}
        {{d.labels}}
        <canvas baseChart width="400" height="400"
        [datasets]="d.data"
        [labels]="d.labels"
        [options]="lineChartOptions"
        [colors]="lineChartColors"
        [legend]="lineChartLegend"
        [chartType]="lineChartType"
        [plugins]="lineChartPlugins"
        (chartHover)="chartHovered($event)"
        (chartClick)="chartClicked($event)">
      </canvas>
    </ion-card>
  </ion-list>

当我显示d.datad.labels在它工作的离子卡中时,我有 2 张带有我的数据的卡。但是<canvas>在我放的地方d.datad.labels我得到了一个错误:

ERROR TypeError: Cannot read property 'length' of undefined

如果相反,画布内的 d.data 和 d.labels 我给了 2 个简单数组,它工作得很好,所以我不明白为什么我不能这样做..

谢谢

标签: angularngfor

解决方案


问题就在这里——

<ion-list *ngFor="let data of full_graph">
  <ion-card *ngFor= 'let d of data'>

您正在尝试将“数据”作为数组而不是作为对象,因为 full_graph 是对象数组而不是数组数组,因此您可以使用以下方法修复上述代码的替换 -

 <ion-list>
   <ion-card *ngFor="let d of full_graph">

推荐阅读