Angular / Chart.js错误:无法创建图表:无法从给定项目获取上下文

San*_*ord 5 javascript angular

这确实是我第一次使用Chart.js,并将其导入到Angular组件中。我现在尝试仅创建一个简单的条形图。我的控制台出现以下错误:

core.controller.js:118 Failed to create chart: can't acquire context from the given item

不知道我在做什么错!

这是我的组件的TS文件:

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

@Component({
  selector: 'app-propel-factor',
  templateUrl: './propel-factor.component.html'
})
export class PropelFactorComponent implements OnInit {

    chart = [];
    labels: any = [];

    data: any = [];

    constructor() { }

    ngOnInit() {
        data.forEach(item => {
            this.labels.push(item.name);
            this.data.push(item.value);
        });

        this.chart = new Chart('canvas', {
            type: 'bar',
            labels: this.labels,
            data: {
                labels: this.labels,
                data: this.data
            },
            options: {
                responsive: true
            }
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

然后我的模板就是:

<div *ngIf="chart">
    <canvas id="canvas">{{ chart }}</canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

我还想继续记录一下,说我尝试了此修复chart.js。创建图表失败:无法从给定项目获取上下文,仍然出现相同的错误!

pix*_*its 8

如果您查看在Chart.js 中创建图表的文档,第一个参数是从 DOM 元素获取的上下文,而不是字符串:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
Run Code Online (Sandbox Code Playgroud)

您可以使用模板变量和 ElementRef 获取对 DOM 元素的引用:

HTML

<div *ngIf="chart">
    <canvas #canvas id="canvas">{{ chart }}</canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

打字稿:

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

@Component({
  selector: 'app-propel-factor',
  templateUrl: './propel-factor.component.html'
})
export class PropelFactorComponent implements OnInit, AfterViewInit {
    @ViewChild('canvas') canvas: ElementRef;

    chart = [];
    labels: any = [];

    data: any = [];

    constructor() { }

    ngOnInit() {
        data.forEach(item => {
            this.labels.push(item.name);
            this.data.push(item.value);
        });

    }
    ngAfterViewInit() {
        this.chart = new Chart(this.canvas.nativeElement.getContext('2d'), {
            type: 'bar',
            labels: this.labels,
            data: {
                labels: this.labels,
                data: this.data
            },
            options: {
                responsive: true
            }
        });

    }

}
Run Code Online (Sandbox Code Playgroud)