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

Angular 8升级至9后Angular Material导入报错求助

解决方案:Angular 9升级后Material模块导入错误

我仔细看了你的AppMaterialModule代码,发现几个明确的问题,这大概率就是导致导入错误的根源,一起来修正:

1. 缺失MatInputModule的导入声明

你在@NgModule的imports和exports数组里都引用了MatInputModule,但在文件顶部完全没有导入这个模块!Angular根本找不到它的定义,自然会报错。

需要在顶部添加:

import { MatInputModule } from '@angular/material/input';

2. MatGridListModule未加入imports数组

你已经在顶部导入了MatGridListModule,但只把它放在了exports数组里。Angular的模块规则是:必须先导入模块,才能导出它,所以得把它加到imports数组中。

3. 清理冗余的模块导入

你导入了MatDividerModule和MatExpansionModule,但既没在imports里注册,也没在exports里对外暴露,这属于冗余代码,可以直接删掉,避免混淆。

修正后的完整代码

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatCardModule } from '@angular/material/card';
import { MatGridListModule } from '@angular/material/grid-list';
// 新增MatInputModule的导入
import { MatInputModule } from '@angular/material/input';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    BrowserAnimationsModule,
    MatButtonModule,
    MatFormFieldModule,
    // 加入MatInputModule到imports
    MatInputModule,
    MatSelectModule,
    MatCardModule,
    // 加入MatGridListModule到imports
    MatGridListModule,
  ],
  exports:[ 
    BrowserAnimationsModule,
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatCardModule,
    MatGridListModule,
  ],
})
export class AppMaterialModule { }

额外的排查步骤(如果修正后仍有问题)

如果上面的修改后还是报错,建议检查以下几点:

  • 确认package.json中@angular/material、@angular/cdk的版本和@angular/core、@angular/cli完全一致(都是9.x.x版本),版本不匹配是升级后常见的问题。
  • 删除node_modules文件夹和package-lock.json(或yarn.lock),然后重新执行npm install,确保依赖安装完整。
  • 清理Angular缓存:执行ng cache clean --force,然后重启你的IDE(有时候IDE的缓存会导致错误提示不更新)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:44:07