Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 653
user2347528 Avatar asked Oct 15 '25 14:10

user2347528


1 Answers

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.

like image 190
Lluís M. Avatar answered Oct 17 '25 08:10

Lluís M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!