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

升级Angular Material 15后MatSelect出现NullInjectorError无提供者问题求助

Angular 15.0.4升级后MatLegacySelect模块注入错误解决

问题背景

将Angular项目从v14升级至15.0.4版本后,使用legacy版本的mat-select组件抛出以下错误:

ERROR NullInjectorError: R3InjectorError(TestModule)[MatSelect -> MatSelect -> MatSelect]: NullInjectorError: No provider for MatSelect!

当前已在material.module.ts中导入MatLegacySelectModule并别名MatSelectModule,且该模块已引入至AppModule,Angular及Angular Material版本均为15.0.4。

解决方案

  • 检查TestModule的依赖导入
    报错指向TestModule,说明该模块未正确引入包含MatSelect(别名)的模块。若TestModule是独立业务模块或测试模块,需直接导入MaterialModule,或单独导入MatLegacySelectModule(别名后的MatSelectModule)。例如:

    // TestModule中
    import { MaterialModule } from './path/to/material.module';
    
    @NgModule({
      imports: [MaterialModule, ...],
      declarations: [YourTestComponent]
    })
    export class TestModule {}
    

    若是单元测试的spec文件,需在TestBed.configureTestingModule的imports数组中添加对应模块:

    TestBed.configureTestingModule({
      imports: [MaterialModule],
      declarations: [YourComponent]
    });
    
  • 确认别名配置正确性
    确保material.module.ts中正确导入并导出别名后的模块,写法如下:

    import { NgModule } from '@angular/core';
    import { MatLegacySelectModule as MatSelectModule } from '@angular/material/legacy-select';
    
    @NgModule({
      imports: [MatLegacySelectModule],
      exports: [MatSelectModule]
    })
    export class MaterialModule {}
    

    重点是exports数组中需导出别名后的MatSelectModule,确保其他模块导入MaterialModule时能获取到正确的组件提供者。

  • 清理项目缓存并重建
    升级后缓存可能导致依赖解析异常,执行以下命令清理缓存并重新构建:

    ng cache clean
    ng build
    # 若为测试场景,执行
    ng test
    
  • 验证依赖版本一致性
    检查package.json中@angular/core、@angular/material等核心依赖版本是否均为15.0.4,避免版本不一致导致的兼容性问题。

内容的提问来源于stack exchange,提问作者rami-sf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:00:46