Chartjs-Ng2-charts / chart.js – How to set doughnut/pie chart color on specific labels programatically?

1πŸ‘

βœ…

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.

Leave a comment