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

Angular集成ng2-charts遇NG0303错误:canvas属性绑定失败求助

Angular 11.2 中 ng2-charts NG0303 错误解决方法

问题重现

在 Angular 11.2 项目中执行以下操作后,页面加载抛出 NG0303 系列错误:

  1. 安装 ng2-charts 预览版:npm install ng2-charts@next --save,版本为 ^3.0.0-rc.7
  2. 安装 chart.js:npm install chart.js --save,版本为 ^2.9.4
  3. 安装 schematics 并更新依赖:npm install --save-dev ng2-charts-schematics 及 npm install
  4. 启动项目:ng serve -o

错误信息:

NG0303: Can't bind to 'type' since it isn't a known property of 'canvas'.
NG0303: Can't bind to 'datasets' since it isn't a known property of 'canvas'.
NG0303: Can't bind to 'labels' since it isn't a known property of 'canvas'.
NG0303: Can't bind to 'options' since it isn't a known property of 'canvas'.
NG0303: Can't bind to 'plugins' since it isn't a known property of 'canvas'.
NG0303: Can't bind to 'legend' since it isn't a known property of 'canvas'.

饼图组件模板代码:

<canvas baseChart
[type]="'pie'"
[datasets]="pieChartDatasets"
[labels]="pieChartLabels"
[options]="pieChartOptions"
[plugins]="pieChartPlugins"
[legend]="pieChartLegend">

饼图组件逻辑代码:

import { Component } from '@angular/core';
import { ChartType, ChartOptions } from 'chart.js';

@Component({
selector: 'app-pie-chart',
templateUrl: './pie-chart.component.html',
styleUrls: ['./pie-chart.component.css']
})

export class PieChartComponent {
// Pie
public pieChartOptions: ChartOptions<'pie'> = {
responsive: false,
};
public pieChartLabels = [ [ 'Download', 'Sales' ], [ 'In', 'Store', 'Sales' ], 'Mail Sales' ];
public pieChartDatasets = [ {
data: [ 300, 500, 100 ]
} ];
public pieChartLegend = true;
public pieChartPlugins = [];
}

已在模块中声明 PieChartComponent,父组件通过 <app-pie-chart></app-pie-chart> 引入。

问题原因

ng2-charts 3.x 版本采用模块化设计,baseChart 指令及相关绑定属性(type、datasets 等)都封装在专门的模块中。如果没有在组件所属的 NgModule 中导入对应的模块,Angular 无法识别这些指令和属性,会将其误认为是原生 <canvas> 元素的属性,从而抛出 NG0303 错误。

官方相关讨论中,大量用户遇到相同问题,核心原因均为未导入 ng2-charts 的模块,维护人员明确指出必须导入对应模块才能使用相关指令。

解决方案

在 PieChartComponent 所属的 NgModule 中导入 ChartsModule(通用模块,支持所有图表类型)或 PieChartModule(仅支持饼图,更轻量化):

修改后的模块代码示例:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PieChartComponent } from './pie-chart.component';
// 导入ng2-charts模块,二选一即可
import { ChartsModule } from 'ng2-charts'; 
// import { PieChartModule } from 'ng2-charts';

@NgModule({
  declarations: [PieChartComponent],
  imports: [
    CommonModule,
    ChartsModule // 替换为 PieChartModule 也可
  ],
  exports: [PieChartComponent] // 若父组件在其他模块中使用,需导出该组件
})
export class PieChartModule { }

保存修改后重启项目,错误即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:57:21