[英]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.