const gainContext = this.gainRef.nativeElement.getContext('2d')
gainContext.canvas.height = '300px'
new Chart(gainContext, createChartConfig(gainConfig))
function createChartConfig({type, labels, data, label, color}: ChartConfig): ChartConfiguration<"line">{
console.log('3 Chart.defaults', Chart.defaults)
return {
type: "line",
data: {
labels,
datasets: [
{
label,
data,
borderColor: color,
stepped: false,
fill: false
}
]
}
}
这不起作用:它无法识别官方文档中必须的类型属性。
let myChart = new Chart(gainContext, { 类型:'线',
我做错了什么?
我们可以通过三种方式做到这一点
一行导入所有内容:
import Chart from 'chart.js/auto';
import { Chart, registerables } from 'chart.js';
然后注册所有组件
Chart.register(...registerables);
通过导入并注册 @Tatyana Molchanova 评论的所需部分
import { Chart, ChartConfiguration, LineController, LineElement, PointElement, LinearScale, Title} from 'chart.js'
然后在实例化新图表之前将其注册到组件中
Chart.register(LineController, LineElement, PointElement, LinearScale, Title);
这里是 Angular 12。高列夫的回答对我有用。我必须使用:
import { Chart, registerables } from 'chart.js';
export class ChartTest {
constructor() {
Chart.register(...registerables);
}
// methods to actually make the chart per documentation
}
您会收到错误,因为您需要包含来自 Chart.js/auto 的图表,而不是来自 Chart.js:
import { Chart } from 'chart.js/auto'
文档中明确说明了这一点:
https://www.chartjs.org/docs/latest/getting-started/integration.html#helper-functions
或者你需要像这样使用动态导入:
const { Chart } = await import('chart.js')
https://www.chartjs.org/docs/latest/getting-started/integration.html#commonjs
*检查版本 ^4 Сhart.js
请升级 npm 包,它对我有用
npm i [email protected]
这在 Angular 14 中对我有用,Bob Ramsey 回答说:
import { Chart, registerables } from 'chart.js';
export class ChartTest {
constructor() {
Chart.register(...registerables);
}
// methods to actually make the chart per documentation
}