mafortis
mafortis

Reputation: 7128

Angular canvas is undefined

I am using chart.js in ionic angular app and I get this error:

this.barCanvas is undefined

Code

HTML

<ion-card-content>
  <canvas #barCanvas></canvas>
</ion-card-content>

Component

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

export class DashboardPage implements OnInit {
 @ViewChild('barCanvas', {static: true}) barCanvas: ElementRef;

 private barChart: Chart;

 constructor(...){...}

 ionViewDidEnter() {
   this.barChartFunction();
 }

 barChartFunction() {
  this.barChart = new Chart(this.barCanvas.nativeElement, {
    type: 'bar',
    data: {
      labels: ['One', 'Two', 'Three', 'Four', 'Five', 'Six'],
      datasets: [
        {
          label: '# of Submit',
          data: [1,2,3,4,5,6],
          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
            }
          }
        ]
      }
    }
  });
 }
}

any idea?

Upvotes: 0

Views: 2077

Answers (2)

mafortis
mafortis

Reputation: 7128

Solved

I've compiled micronyks answer with other codes and it's working now.

Here is how I've done it:

// Pay attention to added `read: ElementRef` (the most important part is this code
@ViewChild('barCanvas', {static: false, read: ElementRef}) barCanvas: ElementRef;

Then I added AfterViewInit to my component and placed my loading code into that

ngAfterViewInit() {
  setTimeout(() => {
    this.barChartFunction();
  }, 6000);
}

barChartFunction() {
  // my charts code...
}

Hope it comes handy for those in need.

Upvotes: 1

micronyks
micronyks

Reputation: 55443

I don't understand IONIC but,

I'm sure that ionViewDidEnter function runs before ngAfterviewInit life cycle hook of Angular component.

ViewChild instance get initialized or accessible ONLY in/after ngAfterViewInit life cycle hook.

So, You have to make sure that ionViewDidEnter runs once viewChild instance is accessible or make sure to run barChartFunction function from ngAfterViewInit function.

Upvotes: 0

Related Questions