升级Angular v17后部分Angular Material组件无法正常工作
问题描述
把Angular应用升级到v17版本并搭配Angular Material使用,升级前已经删掉了所有旧版组件,但升级Angular Material到v17后,mat-select、mat-dialog这类组件失效:点击mat-select没反应,DOM里能找到元素,但丢失了Angular Material的默认CSS属性,没法正常显示。
怀疑问题和Overlay有关,因为受影响的大多是点击后弹出浮层的组件,比如dialog和select。
我的material.scss配置如下:
// hue. Available color palettes: https://material.io/design/color/ $rds-npm-ng-service-advisor-primary: mat.define-palette($sun-yellow); // $rds-npm-ng-service-advisor-secondary: mat-palette($warranty-pro); $rds-npm-ng-service-advisor-accent: mat.define-palette($green); // The warn palette is optional (defaults to red). $rds-npm-ng-service-advisor-warn: mat.define-palette(mat.$red-palette); $rds-npm-ng-service-advisor-warn: mat.define-palette(mat.$red-palette); // Create the theme object (a Sass map containing all of the palettes). $rds-npm-ng-service-advisor-theme: mat.define-light-theme($rds-npm-ng-service-advisor-primary, $rds-npm-ng-service-advisor-accent, $rds-npm-ng-service-advisor-warn); // Include theme styles for core and each component used in your app. // Alternatively, you can import and @include the theme mixins for each component // that you are using. @include mat.all-component-themes($rds-npm-ng-service-advisor-theme);
排查与修复方案
检查Overlay模块是否导入:Angular Material v17中,Overlay相关功能需要单独导入
OverlayModule,在根模块或共享模块里添加:import { OverlayModule } from '@angular/cdk/overlay'; @NgModule({ imports: [ // ...其他模块 OverlayModule ] }) export class YourModule { }确认主题样式注入正确:
- 先检查
material.scss有没有在angular.json的styles数组里配置正确,路径不能出错:"styles": [ "src/styles.scss", "src/material.scss" // 确认这个路径和实际文件位置一致 ] - 如果自定义调色板
$sun-yellow、$green没有正确定义,先换成Angular Material内置的调色板测试:$rds-npm-ng-service-advisor-primary: mat.define-palette(mat.$yellow-palette); $rds-npm-ng-service-advisor-accent: mat.define-palette(mat.$green-palette);
- 先检查
组件模块导入要完整:
用到的组件对应的模块必须导入,比如MatSelectModule、MatDialogModule,别遗漏:import { MatSelectModule } from '@angular/material/select'; import { MatDialogModule } from '@angular/material/dialog'; @NgModule({ imports: [ // ...其他模块 MatSelectModule, MatDialogModule ] })清理缓存重新构建:
执行命令清理Angular缓存,避免旧样式残留影响:ng cache clean ng build --prod
内容的提问来源于stack exchange,提问作者Alan Dolan
相关产品推荐
相关产品推荐

