[英]Creating dynamic arrays in Angular2
I am building a chart.js function in my angular2 web application. 我正在我的angular2 Web应用程序中构建一个chart.js函数。 I want the bars in a bar chart to be red or green depending if their value is above or below a certain threshold.
我希望条形图中的条形为红色或绿色,具体取决于其值是高于还是低于某个阈值。 At the moment, I have a static solution which looks like this:
目前,我有一个静态解决方案,如下所示:
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
]
}
];
However, this is messy and feels like overkill. 但是,这很混乱,感觉像是过分杀伤力。 I need a solution which will support the dynamic update of my data and simply compare the value to a threshold and return one or the other color.
我需要一种解决方案,该解决方案将支持我的数据的动态更新,并且只需将值与阈值进行比较并返回一种或另一种颜色即可。 This has to be done in a way that I can bind to in an Angular2 Template.
这必须以我可以绑定到Angular2模板中的方式完成。 How should I do this?
我应该怎么做?
Here is the html: 这是html:
<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [colors]="colors" [options]="barChartOptions" [legend]="barChartLegend"
[chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)">
</canvas>
In your html: 在您的html中:
...[colors]="getColors()"
In your .ts file: 在您的.ts文件中:
getColors() {
return [{
backgroundColor: this.barChartData.map(d => d > threshold ? red : green)
}];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.