简体   繁体   中英

ng2-charts: How to set Title of chart dynamically in typescript

Using "ng2-charts": "^1.6.0". I have a line chart like this:

<canvas baseChart
              [datasets]="lineChartData"
              [labels]="lineChartLabels"
              [options]="lineChartOptions"
              [colors]="lineChartColors"
              [legend]="lineChartLegend"
              [chartType]="lineChartType"
              (chartHover)="chartHovered($event)"
              (chartClick)="chartClicked($event)"></canvas>
    </div>

I have a variable that is setting the options like this:

this.lineChartOptions = {
      responsive: true,
      animation: {
        duration: 5000, // general animation time
      },
      scales: {
        xAxes: [{
          type: 'time',
          distribution: 'series'
        }]
      },
      title: {
        display: true,
        text: this.getChartTitle()
      }
    }
    this.lineChartOptions.update();
  }

Here is the getChartTitle method.

getChartTitle(): string[] {
   const data = this.chartData.map(point => point.y); // grab only points within the visible range

return ['ChartName',
        '(Data for ' + this.startDate + ' to ' + this.endDate + ')',
        '[<b>Avg Value:</b> ' + Math.round(data.reduce((a, b) => a + b, 0) / data.length * 100) / 100 +
        '%<b>Min Value:</b> ' + Math.round(Math.min.apply(null, data) * 100) / 100 +
        '%<b>Max Value:</b> ' + Math.round(Math.max.apply(null, data) * 100) / 100 + '%]'];
      }

I need to update the chart title from the chart data because I would like the Avg, Max and Min values in the chart title.

But looks like the chart options are being assigned before the data is being bound to the chart. Is it possible to set the title after the data is available?

Sorry for the late response but after experiencing the very same issue and solving it, I decided to post the answer anyways so the next ones coming to this thread can solve it.

The issue is that apparently only changes made to data and labels are considered to redraw the chart. So if you need to change other aspects of the table you might want to use:

this.chart.refresh();

Don't forget to reference the view:

@ViewChild(BaseChartDirective) chart;

That will redraw the chart with your latest changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM