angular-chartjs icon indicating copy to clipboard operation
angular-chartjs copied to clipboard

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

Open nukec opened this issue 6 years ago • 9 comments

For anyone who has an issue with angular 5 and canvas, you have to do it like this:

Html:

<div *ngIf="chart">
    <canvas #myCanvas>{{ chart }}</canvas>
</div>

Use viewchild for angular, don't use js getelementbyid:

@ViewChild('myCanvas') myCanvas: ElementRef;
    public context: CanvasRenderingContext2D;

Method inside component:

gettest(): void{
    this.weatherApi
    .dailyForecast()
    .subscribe(res => {
      
        let temp_max = res['list'].map(res => res.main.temp_max);
        let temp_min = res['list'].map(res => res.main.temp_min);
        let alldates = res['list'].map(res => res.dt)

        let weatherDates = []
        alldates.forEach((res) => {
            let jsdate = new Date(res * 1000)
            weatherDates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
        })

        this.context = (<HTMLCanvasElement>this.myCanvas.nativeElement).getContext('2d');
        this.chart = new Chart(this.context, {
            type: 'line',
            data: {
              labels: weatherDates,
              datasets: [
                { 
                  data: temp_max,
                  borderColor: "#3cba9f",
                  fill: false
                },
                { 
                  data: temp_min,
                  borderColor: "#ffcc00",
                  fill: false
                },
              ]
            },
            options: {
              legend: {
                display: false
              },
              scales: {
                xAxes: [{
                  display: true
                }],
                yAxes: [{
                  display: true
                }],
              }
            }
          });

    })

as you can see you have to properly access context. also initialization of this should be in:

ngAfterViewInit() {
    this.gettest();
  }

nukec avatar Jun 04 '18 12:06 nukec

Great! It worked. But it throws this error: ChartsComponent.html:1 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: '. Current value: 'ngIf: [object Object]'. at viewDebugError (core.js:7393) at expressionChangedAfterItHasBeenCheckedError (core.js:7381) at checkBindingNoChanges (core.js:7483) at checkNoChangesNodeInline (core.js:10344) at checkNoChangesNode (core.js:10333) at debugCheckNoChangesNode (core.js:10936) at debugCheckDirectivesFn (core.js:10864) at Object.eval [as updateDirectives] (ChartsComponent.html:1) at Object.debugUpdateDirectives [as updateDirectives] (core.js:10853) at checkNoChangesView (core.js:10232)

mustafamukadam avatar Jul 17 '18 07:07 mustafamukadam

Just remove that from div declartion *ngIf="chart"

devcdcc avatar Aug 06 '18 11:08 devcdcc

also if you have blinks or render problems try to make different component and call it inside your main component. it works better

nicholasp avatar Aug 15 '18 08:08 nicholasp

This is used to create graphs dynamically?, i mean, I have some data and I have to create graphs for every iteration I do in a cycle.

AlejoMartinez85 avatar Oct 08 '18 16:10 AlejoMartinez85

I m not facing error after applying the given above changes, but there is no chart visible on page

Vino16491 avatar Nov 01 '18 14:11 Vino16491

I've changed the code in template and errors stopped showing up. Chart is ok:

<div>
  <canvas #myCanvas></canvas>
</div>

Grzegorzsa avatar Nov 05 '18 19:11 Grzegorzsa

In my case, I was using ngIf on canvas and then I moved it to its parent div. In both cases I was getting this error: chart.js Failed to create chart: can't acquire context from the given item.

So I changed ngIf to ngStyle with display: (condition)? none: block. And it worked for me

MayankArora20 avatar Apr 27 '20 09:04 MayankArora20

wow, great job, this solved my 2 days of efforts in 10 mins, thanks you so much

yudhi115 avatar Feb 16 '21 10:02 yudhi115

If anyone else gets this same issue and is searching for the cause, bare this in mind: if using standard JS rather than JQuery the <SCRIPT> tag containing the chartJS elements must be loaded AFTER the HTML canvas elements to which they refer.

MHCreations avatar Jun 30 '21 19:06 MHCreations