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

Angular10导入MatIconRegistry时出现NG6002/NG6003错误如何解决?

错误成因
  1. 核心配置错误:MatIconRegistry 是 @angular/material/icon 提供的服务类,不属于 NgModule、组件、指令、管道的范畴,无法放入 @NgModule 的 imports、exports 数组中。你将其加入了自定义 MaterialModule 的导入导出列表,Angular 编译器无法识别该类为合法的 NgModule 成员,直接抛出 NG6002、NG6003 错误。
  2. 连锁报错:由于自定义 MaterialModule 本身存在配置错误,所有依赖导入该模块的业务模块(FoodTypeModule、FoodItemModule、IngredientModule 等)、根模块 AppModule 都会触发「依赖模块存在错误」的连锁异常。

注:报错提示中提到的 ngcc 处理异常、Ivy 不兼容属于通用误导提示,你当前使用的 Angular 10.0.14 搭配 @angular/material 10.2.7 版本本身是兼容的,不需要升级版本。

可行解决方法
  • 修正 MaterialModule 配置
    打开 src/app/material/material.module.ts,删除 @NgModule 装饰器的 imports、exports 数组中的 MatIconRegistry 条目。如果需要使用图标组件,仅需在导入导出列表中保留 MatIconModule 即可。
  • 正确使用 MatIconRegistry
    该服务通过依赖注入使用,不需要在模块中声明导入导出,需要使用时直接在组件/服务的构造函数中注入即可,示例如下:
    import { MatIconRegistry } from '@angular/material/icon';
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Component({
      selector: 'app-your-component',
      templateUrl: './your-component.component.html'
    })
    export class YourComponent {
      constructor(
        private matIconRegistry: MatIconRegistry,
        private domSanitizer: DomSanitizer
      ) {
        // 自定义图标注册逻辑
        this.matIconRegistry.addSvgIcon(
          'custom-icon',
          this.domSanitizer.bypassSecurityTrustResourceUrl('assets/icons/custom.svg')
        );
      }
    }
    
    如果需要全局注册自定义图标,也可以在 AppModule 的构造函数中注入该服务完成注册。
  • 清理缓存重启服务
    修改完成后删除项目下的 node_modules/.cache 目录,再重启 ng serve 服务,清理缓存编译产物后错误即可消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:06:03