gpt4 book ai didi

javascript - Angular/Chart.js 错误 : Failed to create chart: can't acquire context from the given item

转载 作者:太空狗 更新时间:2023-10-29 17:51:34 40 4
gpt4 key购买 nike

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

core.controller.js:118 无法创建图表:无法从给定项目获取上下文

不确定我在这里做错了什么!

这是我的组件的 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
}
});
}

}

然后我的模板很简单:

<div *ngIf="chart">
<canvas id="canvas">{{ chart }}</canvas>
</div>

我还想公开表示我尝试了此修复 chart.js Failed to create chart: can't acquire context from the given item仍然会出现同样的错误!

最佳答案

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

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {

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

HTML

<div *ngIf="chart">
<canvas #canvas id="canvas">{{ chart }}</canvas>
</div>

typescript :

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
}
});

}

}

关于javascript - Angular/Chart.js 错误 : Failed to create chart: can't acquire context from the given item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48046386/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com