[Chartjs]-Changing Dataset for a chart in angular 10

1๐Ÿ‘

โœ…

You need to destroy the chart and then recreate it

Create a function in your area-chart-component.ts

updateChart() {
    this.chart.destroy();
    const chartRefEl = this.chartRef.nativeElement;
    const ctx = chartRefEl.getContext('2d');
    this.chart = new Chart(ctx, {
      type: this.shadow ? 'lineWithShadow' : 'line',
      data: this.data,
      options: this.options,
    });
  }

and then call this function

callMe(option: number) {
    if (option === 1) {
      this.AreaChartComponentRef.data = areaChartDataFemale;
      this.AreaChartComponentRef.updateChart();

    } else {
      // this.isFemaleSelected = false;
      this.AreaChartComponentRef.data = areaChartDataMale;
      this.AreaChartComponentRef.updateChart();
      
    }

0๐Ÿ‘

If you want to get the component instance you need to use @ViewChild() like :

In your component.ts :

@ViewChild('chartComponent', {static: true}) chartComponent: AreaChartComponent;

In your component.html :

<app-area-chart
  [shadow]="true"
  class="chart"
  [options]="chartDataConfig.areaChartOptions"
  [data]="areaData"
  #chartComponent>
</app-area-chart>

Finaly you can access it in your component.ts with

this.chartComponent.updateChart();

Leave a comment