Reputation: 1170
I have a list of transactions which return status
as chart labels and count
as chart data. My labels are often ['cancelled', 'completed', 'rejected']
, but sometimes the data returns ['cancelled', 'completed', 'error', 'pending', 'rejected]
. How to set different color for each label?
My code so far:
statusCount: StatusCount[] = [];
loaded = false;
// Doughnut
public chartData = [];
public chartLabels = [];
public chartType = 'doughnut';
public chartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'right'
}
};
private chartColors: any[] = [{ backgroundColor: ['#E91E63', '#00BFA5', '#ff1744'] }];
constructor(
private apiService: ApiService
) {
}
ngOnInit() {
this.getTransactionStatus();
}
getTransactionStatus() {
this.apiService.getTransactionStatus().subscribe((res: any) => {
this.statusCount = res;
for (const i of this.statusCount) {
this.chartData.push(i.count);
this.chartLabels.push(i.status);
}
this.loaded = true;
}, error => {
console.log(error);
});
}
Upvotes: 0
Views: 881
Reputation: 3994
You can set chartColors
also in your getTransactionStatus
method.
It would look something like this (assuming that your statusCount
object has a color property:
public chartColors: any[] = [{ backgroundColor: [] }];
constructor(
private apiService: ApiService
) {
}
ngOnInit() {
this.getTransactionStatus();
}
getTransactionStatus() {
this.apiService.getTransactionStatus().subscribe((res: any) => {
this.statusCount = res;
for (const i of this.statusCount) {
this.chartData.push(i.count);
this.chartLabels.push(i.status);
this.chartColors[0].backgroundColor.push(i.color);
}
this.loaded = true;
}, error => {
console.log(error);
});
}
Note that your chartColors
object should be public (like the chartData
, chartLabelse
, etc.) to be visible to the HTML (it will work in dev mode but it won't build unless it is public.
Upvotes: 1