4

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?

3 Answers 3

4

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.

2

Just came across the same issue in 2022 and the accepted answer does not work for me. Just in case someone is now looking into this again as I was, I'll leave the workaround that finally worked for me.

Having this property in the Angular component

chartOptions!: ChartOptions;

And then in the ngOnInit() I have

// define chart options
this.chartOptions = this.getChartOptions();

Which then returns the data at a time when it is available

getChartOptions(): ChartOptions {
    return {
      responsive: true,
      title: {
        display: true,
        text: this.getChartTitle()
      },
    };
  }

CAUTION for 2023

if it's still not working, we need to set it via plugins, not ChartOptions object anymore with ng2-charts. See more on https://www.chartjs.org/docs/latest/configuration/title.html

So in short, we can use another function like this :

GetChartOptions(newTitle: string): ChartConfiguration['options']
{
    return {
      plugins: {
        title: {
          display: true,
          text: newTitle,
          font: {
            size: 20
          }
        }
      }
    };
}

We change by change the property map (see the [options]="lineChartOptions", one way map) on the canvas html

<canvas
  baseChart
  class="chart"
  [id]="'line'"
  [data]="lineChartData"
  [options]="lineChartOptions"
  [type]="lineChartType"
  [legend]="true"
></canvas>

The actions can be done with calling ChangeTitle(), and in that code calling GetChartOptions('newTitle anything aaaa') that fill the one way map property

  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;

  public lineChartOptions: ChartConfiguration['options'] = {
    plugins: {
      title: {
        display: true,
        text: "Chart Line",
        font: {
          size: 20
        }
      }
    }
  }

  public ChangeTitle()
  {
     this.lineChartOptions = this.GetChartOptions("aaaa");
     this.chart?.chart?.update(); // Don't forget to update, if not it won't be refreshed!
  }

You can set the value via input from user, or anything you want and put it into the options builder function..

0

With ng2-charts v4.1.1 (chartjs v4.x.x), the render() function works for me:

@ViewChild(BaseChartDirective) chart;

...

this.chart?.render();

From the docs here

Triggers a redraw of all chart elements. Note, this does not update elements for new data. Use .update() in that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.