Angular10导入MatIconRegistry时出现NG6002/NG6003错误如何解决?
错误成因
- 核心配置错误:
MatIconRegistry是@angular/material/icon提供的服务类,不属于 NgModule、组件、指令、管道的范畴,无法放入@NgModule的imports、exports数组中。你将其加入了自定义MaterialModule的导入导出列表,Angular 编译器无法识别该类为合法的 NgModule 成员,直接抛出 NG6002、NG6003 错误。 - 连锁报错:由于自定义
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
该服务通过依赖注入使用,不需要在模块中声明导入导出,需要使用时直接在组件/服务的构造函数中注入即可,示例如下:
如果需要全局注册自定义图标,也可以在 AppModule 的构造函数中注入该服务完成注册。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') ); } } - 清理缓存重启服务
修改完成后删除项目下的node_modules/.cache目录,再重启ng serve服务,清理缓存编译产物后错误即可消失。
内容的提问来源于stack exchange,提问作者Imad Che
相关产品推荐
相关产品推荐

