vlntn
vlntn

Reputation: 370

Chart.js Error: Failed to create chart: can't acquire context from the given item

I am trying to implement a simple chart in my angular app with chart.js. But unfortunately I am getting following error:

Failed to create chart: can't acquire context from the given item

I already found several similar questions here but somehow none of the answers really helped. Does anyone has an idea how to fix this?

task-activity.component.html

        <nb-tab tabIcon="bar-chart-2-outline" tabTitle="Insights">
          <div id="divChart">
            <canvas id="myChart" width="400px" height="400px"></canvas>
          </div>
        </nb-tab>

task-activity.component.ts

import { Component, Input, ViewChild, OnInit, AfterViewInit, TemplateRef } from '@angular/core';
import { Chart }  from 'chart.js';

@Component({
  selector: 'ngx-task-activity',
  templateUrl: './task-activity.component.html',
  styleUrls: ['./task-activity.component.scss'],
})
export class TaskActivityComponent implements OnInit, AfterViewInit {

  chart= [];

  constructor(private dialogService: NbDialogService,
    public organizationService: OrganizationService) {
      this.userId = organizationService.getUserId();
      console.info('this.userId:', this.userId);

      setTimeout(() => {
        this.user = organizationService.getUser();
      }, 2000);

  }

  ngOnInit() {
    this.initData();

    this.chart.push(new Chart('myChart', {
      // The type of chart we want to create
      type: 'bar',
      data: {
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
          datasets: [{
              label: '# of Votes',
              data: [12, 19, 3, 5, 2, 3],
              backgroundColor: [
                  'rgba(255, 99, 132, 0.2)',
                  'rgba(54, 162, 235, 0.2)',
                  'rgba(255, 206, 86, 0.2)',
                  'rgba(75, 192, 192, 0.2)',
                  'rgba(153, 102, 255, 0.2)',
                  'rgba(255, 159, 64, 0.2)'
              ],
              borderColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 206, 86, 1)',
                  'rgba(75, 192, 192, 1)',
                  'rgba(153, 102, 255, 1)',
                  'rgba(255, 159, 64, 1)'
              ],
              borderWidth: 1
          }]
      },
      options: {
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }]
          }
      }
  }));

  }

Upvotes: 0

Views: 675

Answers (1)

Christos Sirmakezis
Christos Sirmakezis

Reputation: 96

This an answer on how to dynamically update an angular-chatr.js chart using the ng2-charts package. Make sure you include node_modules/dist/Chart.min.js to your web manifest, or as a link in your index.html

Please visit this https://stackoverflow.com/a/64793266/12683543

Upvotes: 1

Related Questions