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

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

我正在尝试使用 chart.js 和 angular

创建图表

这里是citydetail.component.html

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

这是 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'
        ]
      }
    });

  }

显示this.canvas未定义。起初我得到这个错误: failed to create chart: can't acquire context from the given item ,并试图解决这个问题。

我对如何进一步进行感到困惑。

canvas 元素将不会被渲染(写入 DOM)直到 chart 为真

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

因为 chart 最初是 undefined,canvas ViewChild 不存在,这解释了为什么“this.canvas 未定义”。

尝试删除 *ngIf="chart" 以测试您的图表。

<canvas #canvas></canvas>