繁体   English   中英

在Angular2中创建动态数组

[英]Creating dynamic arrays in Angular2

我正在我的angular2 Web应用程序中构建一个chart.js函数。 我希望条形图中的条形为红色或绿色,具体取决于其值是高于还是低于某个阈值。 目前,我有一个静态解决方案,如下所示:

  public barChartLabels: string[] = ['06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00', '01:00', '02:00', '03:00', '04:00', '05:00'];
  public barChartType: string = 'bar';
  public barChartLegend: boolean = false;

  public barChartData: any[] = [
    {
      data: [85, 81, 80, 81, 56, 73, 70, 5, 0, 0, 65, 70, 83, 90, 85, 86, 84, 80, 87, 88, 82, 74, 71, 80],
      label: 'Values'
    }
  ];
private colors = [
    {
      backgroundColor: [
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)'
        // Potentially loads more colors
      ]
    }
  ];

但是,这很混乱,感觉像是过分杀伤力。 我需要一种解决方案,该解决方案将支持我的数据的动态更新,并且只需将值与阈值进行比较并返回一种或另一种颜色即可。 这必须以我可以绑定到Angular2模板中的方式完成。 我应该怎么做?

更新:

这是html:

<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [colors]="colors" [options]="barChartOptions" [legend]="barChartLegend"
    [chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)">
</canvas>

在您的html中:

...[colors]="getColors()"

在您的.ts文件中:

getColors() {
  return [{
     backgroundColor: this.barChartData.map(d => d > threshold ? red : green)
   }];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM