You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular集成Chart.js组件报错:类型'string'无法分配给'ChartTitleOptions|undefined'

问题原因

这个报错不是版本兼容问题,是你使用Chart.js v3及以上版本时,配置写法不符合新版API规范导致的。

具体错误点

  • Chart.js v3+版本中title配置已经移动到options.plugins层级下,不再是options的直接子属性
  • options.plugins.title要求传入ChartTitleOptions类型的配置对象,你直接给了字符串'Line Chart',是触发该类型报错的直接原因
  • display属性属于title配置的子属性,你错误放在了options顶级层级下
  • 坐标轴配置写法也不符合v3+规范,新版不再使用yAxes数组格式,改为直接通过轴名(如y)配置
  • 线平滑度属性在v3中从lineTension改名为tension

修正后代码

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

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {
  @Input() stock!: string;
  LineChart:any = []
  constructor() { }

  ngOnInit() {
    this.LineChart = new Chart('linechart', {
      type: 'line',
      data: {
        labels: ['jan', 'fev'],
        datasets: [{
          label: 'Number xxxxxx',
          data: [1, 2],
          fill: false,
          tension: 0.3,
          borderColor: 'red',
          borderWidth: 1
        }]
      },
      options: {
        plugins: {
          title: {
            display: true,
            text: 'Line Chart'
          }
        },
        scales: {
          y: {
            ticks: {
              beginAtZero: true
            }
          }
        }
      }
    });
  }
}

如果你希望继续沿用旧版写法,可以直接将Chart.js降级到2.x版本,无需修改现有配置即可正常运行。

内容的提问来源于stack exchange,提问作者Rudson Rodrigues

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:57:06