ng2-charts update labels and data

前端 未结 12 1106
长发绾君心
长发绾君心 2020-12-03 01:25

I\'m trying to create dynamically a chart using ng2-chart, I get information from an angular 2 service, when I change only labels of chart it works and when I change data on

12条回答
  •  被撕碎了的回忆
    2020-12-03 01:59

    Since I didn't manage to get one of the above solutions to work properly, I want to contribute my solution, in case someone stumbles across this post and also got stuck with the present approaches.

    I have the HTML similar to @mustafa918:

     

    And for the initialisation of the charts data in typescript i have:

    public lineChartData: Array = [
        { data: this.heights, label: 'Heights History', type: 'line', fill: false},
        { data: this.widths, label: 'Widths History', type: 'line', fill: false }];
    

    And for me it worked only by setting the data and labels at the same time and don't use chart.update() - chart is the reference to the BaseChartDirective.

    I loaded the respective data and labels beforehand, so that in this.heights, this.width and this.lineChartLabels are corresponding data.

    E.g. : The entries on heights[i], widths[i] and lineChartLabels[i] match with the element in my elementArray at index i => element ={ "height":30, "width":20, "label":"box"}

    setDatasets() {
    
    //store data in chart references
    var arrHeights = [];
    for (var i in this.heights) {
      arrHeights.push({ x: this.lineChartLabels[i], y: this.heights[i] });
    }
    
    var arrWidths= [];
    for (var i in this.widths) {
      arrWidths.push({ x: this.lineChartLabels[i], y: this.widths[i] });
    }
    
    this.lineChartData[0].data = arrHeights;
    this.lineChartData[1].data = arrWidths;
    

    }

    I hope this helps someone :) Good Luck!

提交回复
热议问题