[Chartjs]-Ng2-charts: How to set Title of chart dynamically in typescript

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.

Leave a comment