【问题标题】:ngfor for array in object with ng2-chartsngfor 用于具有 ng2-charts 的对象中的数组
【发布时间】:2020-10-11 00:08:00
【问题描述】:

我正在尝试使用 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>

当我在 ionic 卡中显示 d.datad.labels 时,我的数据有 2 张卡。但是在&lt;canvas&gt; 里面我放了d.datad.labels 我得到了一个错误:

ERROR TypeError: Cannot read property 'length' of undefined

如果改为在画布内使用 d.data 和 d.labels 我提供 2 个简单数组,它可以完美运行,所以我不明白为什么我不能这样做..

谢谢

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    问题就在这里-

    <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">
    

    【讨论】:

    • 我之前试过了,还是不行。我得到了这个:错误错误:ng-charts 配置错误,需要数据或数据集字段才能在 BaseChartDirective.getDatasets (ng2-charts.js:863) 处呈现图表线。使用我的双 ngFor,我可以使用我的 {{d.data}} => 在离子卡内显示我的值,但在画布内却没有..
    • component.ts 文件中是否有任何名为“data”的变量?
    • 我在一个名为 data 的函数中有一个局部变量
    • 您是否尝试在 *ngFor 循环中将变量名数据更改为其他内容?这让我有点困惑,为什么你需要 2 *ngFor 循环来处理这种情况!
    • 是的,我也这样做了,但它也适合我,但我可以显示数据......不明白为什么我可以显示它而不是绘制它..
    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2017-09-25
    • 2016-08-22
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多