[Chartjs]-How to load gridster with Chart.js dynamically on clicking a button?

2👍

You’re using id inside your component. And while creating a chart you’re referring to the id selector. So aparantly it is re-rendering 1st component that matches the id selector.

You have to generate a new id on each component generation and render that way.

HTML

<div class="chart">
  <canvas [attr.id]="id"></canvas>
</div>

Component

id = Math.floor(Math.random() * 1000);

ngAfterViewInit(): void {
  const chartContext = Chart.getChart(this.id.toString());
  if (chartContext !== undefined) {
    chartContext.destroy();
  }

  this.loadLineChart();
}
loadLineChart() {
    this.myChart = new Chart(this.id.toString(), {
      type: 'line',
      ....
    });
}

Forked Stackbliz

Note:- Since we are generating an id from the component dynamically, we had move the graph plotting code from ngOnInit to ngAfterViewInit (to make sure id generated and updated on UI before query) lifecycle hook.

Leave a comment