我有一个动态的数据是需要被放到里面一个for循环,以显示感兴趣的数据。我测试将动画到0从这个issue也尝试同样的update()函数。
这是我下面的代码
barChartMonth() {
let backgroundColor: any = [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
];
let borderColor: any = [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
];
this.barChart = new Chart(this.barCanvas.nativeElement, {
type: 'bar',
data: {
labels: this.monthcostlabor,
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
for(let bard = 0; bard < this.monthcostlabor.length; bard++){
this.barChart.data.datasets.push({ label: this.monthcostlabor[bard], backgroundColor: backgroundColor[bard], borderColor: borderColor[bard], borderWidth: 1 });
}
this.barChart.data.datasets.forEach(element => {
element.data.push(this.monthcostglobal)
});
this.barChart.update();
}
上面的代码动态地选择颜色,悬停和基于所记录的数据。参见循环。是否有任何其他的方式来解决这个问题?
少数的突出问题是backgroundColor
如何长度和borderColor
可能低于this.monthcostlabor
领导通过undefined
迭代器加载时bard
值。
另外,你为什么不能在构造函数中循环?
this.barChart = new Chart(this.barCanvas.nativeElement, {
type: 'bar',
data: {
labels: this.monthcostlabor,
datasets: this.monthcostlabor.map((elem,i) => ({
label: elem,
backgroundColor: backgroundColor[(i % backgroundColor.length)],
borderColor: borderColor[(i % borderColor.length)],
borderWidth: 1,
data:[this.monthcostglobal] })); // the second push() can be included here?
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
/*
for(let bard = 0; bard < this.monthcostlabor.length; bard++){
this.barChart.data.datasets.push({ label: this.monthcostlabor[bard], backgroundColor: backgroundColor[bard], borderColor: borderColor[bard], borderWidth: 1 });
}
this.barChart.data.datasets.forEach(element => {
element.data.push(this.monthcostglobal)
});
this.barChart.update(); */