The dataset in ng2 charts for bar graph is not setting properly

1.3k Views Asked by At

I am creating a bar chart using ng2 charts library. in the template I have added the following code

<div class="chart-wrapper">
    <canvas baseChart
    [datasets]="getBarChartData()"
    [labels]="barChartLabels"
    [options]="barChartOptions"
    [plugins]="barChartPlugins"
    [legend]="barChartLegend"
    [chartType]="barChartType">
    </canvas>
</div>

In component.ts file I have added the following lines of code, Here I am using a function depending on range I am changing the color of the bar dynamically, but the bar size is not shown properly if I use this line of code it works properly.

barChartData: ChartDataSets[] = [{
    data: [80, 12, 200, 137, 164, 4, 10, 35],
    label: 'A Bar Chart',
    backgroundColor: ['#99ccff', '#808080']
}];

export class BarchartComponent {
    constructor(private data: ChartService) {}
    barChartOptions: ChartOptions = {
        responsive: true
    };
    barChartLabels: Label[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
    barChartType: ChartType = 'bar';
    barChartLegend = true;
    barChartPlugins = [];


    getBarChartData() {
        const dataSets = [80, 12, 200, 137, 164, 4, 10, 35];
        const low = 2;
        const high = 5;
        const colors = [];
        for (let i = 0; i < dataSets.length; i++) {
            if (i >= (low - 1) && i <= (high- 1)) {
                colors.push('#99ccff')
            } else {
                colors.push('#808080')
            }
        }
        const barChartData: ChartDataSets[] = [{
            data: dataSets,
            label: 'A Bar Chart',
            backgroundColor: colors
        }];
        return barChartData;
    }
}

The problem is the bar graph values are not completely displayed. can someone help me how to set the data for bar with the above example. enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is related to Angular change detection that runs constantly and has to evaluate the datasets property of the canvas again and again. This way the chart is constantly updated and Chart.js can no longer draw it correctly.

Avoid using the function getBarChartData() directly in the HTML but create a barChartData property in the component class instead.

<canvas baseChart 
  [datasets]="barChartData"
  ...

This barChartData property could be furnished in the ngOnInit method as follows:

barChartData: ChartDataSets[] = [];
  
ngOnInit() {
  this.barChartData = this.getBarChartData();
}

Please take a look at the following StackBlitz and see how it works.