2017-04-14 37 views
1

我有一个非常简单的折线图,我想在用户单击按钮时添加值。但无论出于何种原因,只有第一个增加的值(在初始值之后)才会显示出来,之后的所有值都会被删除。只有第一个增加值显示在ng2图表线图中

enter image description here

我所知道的this very similar issue,但我已经使用标签,它仍然不是为我工作正常。

我做了一个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(); 
    } 
} 

这是某种形式的bug还是有人知道如何解决这个问题?

回答

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

这实际上可以工作,超级怪异,但感谢! – Staeff