2

I need to display a graph in my Angular project. A simple doughnut chart with 3 datasets. When I try to run the project, the console throws the following error:

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

I've read the documentation, used the templates and even checked on few questions of StackOverflow :

None of them worked and I think that it owes to the typescript doesn't "find" the ID of the < canvas >, but I sincerely don't know what am I doing wrong

Here's the code:

HTML

<canvas #grafico id="grafico">{{ grafico }}</canvas>

TypeScript

    import Chart = require('chart.js');

    grafico: any;

    this.grafico = new Chart('grafico',{
    type:"doughnut",
    data:{
      labels: ['Expirados', 'Sem exames', 'Proximo de expirar'],
      datasets:[
        { // Exames expirados
          data:res[0].num_funcion_expir, // Data from API
          backgroundColor:'#EA3100'
        },
        { // Exames expirados
          data:res[0].num_funcion_sem_exam_ini, // Data from API
          backgroundColor:'#ff6384'
        },
        { // Exames expirados
          data:res[0].num_funcion_expir_prox_exam, // Data from API
          backgroundColor:'#EAA900'
        },
      ]
    },
    options:{
      legend:{
        display:true
      }
    }
  });

Any help is appreciated

2 Answers 2

2

You only need to add this to the html template

<div [hidden]="!grafico"><canvas id="grafico">{{ grafico }}</canvas></div>

Here is an example of Angular using Chart.JS

Sign up to request clarification or add additional context in comments.

1 Comment

I've actually found a way around it. More difficult, though.. So, many thanks for your answer!
0

Refer the canvas with template reference in the component where you are creating the chart.

Component (Use static as true if you are generating the chart in ngOnInit):

@ViewChild('grafico',{static:true}) grafico: Chart = []; 

Template (Because if you are using *ngIf , it removes the element from the dom if the condition evaluates to false) :

<div [hidden]="!grafico"><canvas id="grafico">{{ grafico }}</canvas></div>

Further more, you can debug the applicatio and verify if the chart is getting created properly or not.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.