【问题标题】:ERROR TypeError: "this.canvas is undefined" | Problem with creating a chart with angular and chart.js错误类型错误:“this.canvas 未定义”|使用 angular 和 chart.js 创建图表的问题
【发布时间】:2020-10-11 00:17:03
【问题描述】:

我正在尝试使用 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,并试图解决这个问题。

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

【问题讨论】:

    标签: javascript angular html5-canvas chart.js viewchild


    【解决方案1】:

    chart 为真之前,canvas 元素不会被渲染(写入 DOM)

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

    因为chart最初是undefined,所以画布ViewChild不存在,这就解释了为什么“this.canvas is undefined”。

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

    <canvas #canvas></canvas>
    

    【讨论】:

      猜你喜欢
      • 2022-07-04
      • 1970-01-01
      • 2019-07-20
      • 2019-04-14
      • 2021-09-14
      • 2019-06-20
      • 2021-10-12
      • 2022-11-27
      • 2019-11-04
      相关资源
      最近更新 更多