Desenv Junior
Desenv Junior

Reputation: 141

Building Multiple Charts Using Chart JS in an Angular Application

I created a component to every type of charts (pie, bars, lines...) For example: bar-chart.component.html

<canvas id="{{idChart}}"></canvas>

bar-chart.component.ts

 @Input() idChart:any;

ngOnInit(): void {
    new Chart(this.idChart, {
      type: 'bar',
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple'],
        datasets: [
          {
            label: 'Label Teste',
            data: [19, 12, 10, 8, 7],
            backgroundColor: [
              '#4B79A1',
              '#6693BD',
              '#82AED9',
              '#9ECAF6',
              '#BBE6FF',
            ],
            borderColor: [
              '#4B79A1',
              '#6693BD',
              '#82AED9',
              '#9ECAF6',
              '#BBE6FF',
            ],
            borderWidth: 1,
          },
        ],
      },
      options: {
        maintainAspectRatio: false,
        responsive: true,
        scales: {
          y: {
            beginAtZero: true,
          },
        },
      },
    });   }

I have a component called home and it should contain several charts:

<div class="barCharts">
  <app-bar-chart idChart='myBarChart1'></app-bar-chart>
  <app-bar-chart idChart='myBarChart2'></app-bar-chart>
  <app-bar-chart idChart='myBarChart3'></app-bar-chart>
</div>

however I have two types of errors:

Failed to create chart: can't acquire context from the given item Because of the ID send my input property

and

Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused.

because there is more than on chart(I have different Ids)

I tried to put it inside a variable and then destroy the chart instance using:

ngOnInit() {
this.myChart ? this.myChart.destroy() : null
...
}

But I was not successful

Upvotes: 2

Views: 1576

Answers (1)

uminder
uminder

Reputation: 26150

Try to put your chart creation code inside ngAfterViewInit() instead of ngOnInt().

The ngAfterViewInit() is invoked once the component view is initialized. At this point you can be sure, the canvas exists.

For further details, please consult lifecycle event sequence from the Angular documentation.

Upvotes: 0

Related Questions