1

我有一个非常简单的折线图,当用户单击按钮时,我想在其中添加值。但无论出于何种原因,只会显示添加的第一个值(在初始值之后),并且之后的所有值都会被削减。

在此处输入图像描述

我知道这个非常相似的问题,但我已经在使用标签,但它仍然无法正常工作。

我已经为我的问题制作了一个plunkr版本,但这基本上是我的代码:

模板:

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

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

零件:

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();
    }
}

这是某种错误还是有人知道如何解决这个问题?

4

2 回答 2

1

删除标签的切片,这应该可以解决问题

这意味着您的 addRandomValue() 应该如下所示:

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();
}
于 2017-04-22T15:29:52.587 回答
0

这是一个有点众所周知的问题。如果您查看 ng2-chart 的示例,您会注意到条形图声明下方的注释(https://github.com/valor-software/ng2-charts/blob/master/demo/src/ app/components/charts/bar-chart-demo.ts)。

简而言之,您必须克隆数据,在克隆上完成 CRUD,然后将数据重新分配给原始变量,以便识别更改。

于 2017-04-16T13:30:09.617 回答