Search code examples
javascriptangularhtml5-canvaschart.jsviewchild

ERROR TypeError: "this.canvas is undefined" | Problem with creating a chart with angular and chart.js


I'm trying to create a Chart with chart.js and angular

Here's citydetail.component.html

<div *ngIf="chart">
    <canvas #canvas></canvas>
</div>

here's the code for citydetail.component.ts

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Citydetails } from '../shared/citydetails';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Location } from '@angular/common';
import { switchMap, scan } from 'rxjs/operators';
import { Chart } from 'chart.js';
// import * as Chart from 'chart.js';


@Component({
  selector: 'app-citydetail',
  templateUrl: './citydetail.component.html',
  styleUrls: ['./citydetail.component.scss']
})
export class CitydetailComponent implements OnInit, AfterViewInit {
  @ViewChild('canvas', {static: false}) canvas: ElementRef;

  public context: CanvasRenderingContext2D;

  chart: Chart;
  citydetails: Citydetails;
  

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private location: Location,
  ) { }

  ngOnInit(): void {
    this.route
      .queryParams
      .subscribe( params => {
        console.log("Data: ", JSON.parse(params['city']));
        this.citydetails = JSON.parse(params['city']);
        

      });
    
    // this.createChart();
      
  }

  ngAfterViewInit(): void {
    this.context = this.canvas.nativeElement.getContext('2d');
    this.chart = new Chart(this.context, {
      type: 'pie',
      data: {
        datasets: [{
          backgroundColor: ["#3498db","#95a5a6","#9b59b6"],
          data: [this.citydetails.active, this.citydetails.recovered, this.citydetails.deceased]
        }],
        labels: [
          'Active',
          'Recovered',
          'Deceased'
        ]
      }
    });

  }

It's showing that this.canvas is undefined. At first I was getting this error: failed to create chart: can't acquire context from the given item , and trying to solve that lead me to this.

I am confused on how to proceed further.


Solution

  • The canvas element will not be rendered (written to the DOM) until chart is true

    <div *ngIf="chart">
        <canvas #canvas></canvas>
    </div>
    

    Because chart is initially undefined, the canvas ViewChild does not exist, which explains why "this.canvas is undefined".

    Try removing *ngIf="chart" to test your chart.

    <canvas #canvas></canvas>