Only first value added gets displayed in ng2-chart linechart

I have a very simple line chart where I want to add values when a user clicks on a button. But for whatever reason only the first value added (after initial values) will get displayed and all values afterwards are kind of cut of.

enter image description here

I'm aware of this very similar issue but I'm already using labels and it's still not working correctly for me.

I've made a plunkr version of my problem, but here is basically my code:

Template:

<div style="display: block">
    <canvas baseChart
            [options]="chartOptions"
            [data]="chartData"
            [labels]="chartLabels"
            [chartType]="chartType"></canvas>
</div>

<button (click)="addRandomValue()">Add Random value</button>

Component:

export class ChartComponent implements OnInit {
    public chartType: string;

    public chartData: number[];
    public chartLabels: string[];

    public chartOptions: any = {
        responsive: true,
        maintainAspectRatio: false
    };

    ngOnInit(): void {
        this.chartType = 'line';
        this.chartLabels = [ '1', '2', '3' ];
        this.chartData = [ 0, 10, 20 ];
    }

    addRandomValue(): void {
        this.chartData.push(Math.random() * 10 + 10);
        this.chartLabels.push(this.chartData.length + '');

        // weird workaround for refreshing data, works fine
        // for all other chart types I tried it on
        this.chartData = this.chartData.slice();
        this.chartLabels = this.chartLabels.slice();
    }
}

Is this some kind of bug or does anyone know how to work around this issue?

Answers:

Answer

Remove the slice of the labels, that should do the trick

Which means your addRandomValue() should look like this:

addRandomValue(): void {
    this.chartData.push(Math.random() * 10 + 10);
    this.chartLabels.push(this.chartData.length + '');

    // weird workaround for refreshing data, works fine
    // for all other chart types I tried it on
    this.chartData = this.chartData.slice();
}
Answer

That's a somewhat known issue. If you look at the examples for ng2-chart you'll notice a comment written beneath the declaration of the bar-chart (https://github.com/valor-software/ng2-charts/blob/master/demo/src/app/components/charts/bar-chart-demo.ts).

To put it in a nutshell, you have to clone the data, get your CRUD done on the clone, and reassign the data to the original variable so the change is recognized.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.