Angular Material 5中MatSnackBar导入报错,是否需更换版本?
不需要更换版本,问题出在你的模块导入方式上
你遇到的错误根本不是版本问题——Angular Material 5.0.0完全支持MatSnackBar,错误的核心是你错误地将非NgModule类放到了@NgModule的imports数组中。
错误原因解析
MatSnackBar是一个服务类,MatSnackBarConfig是一个配置类,它们都不是Angular模块(没有@NgModule装饰器)。而imports数组只能接受带有@NgModule的模块类,所以编译器才会抛出这个错误:
Unexpected value 'MatSnackBar' imported by the module 'AppModule'. Please add a @NgModule annotation.
正确的配置方式
你需要导入的是MatSnackBarModule(这才是包含MatSnackBar服务的Angular模块),而不是直接导入MatSnackBar和MatSnackBarConfig。修改你的app.module.ts如下:
// app.module.ts ... // 只需要导入MatSnackBarModule import { MatSnackBarModule, ... } from '@angular/material'; ... @NgModule({ declarations: [...], imports: [MatSnackBarModule, ...], // 这里放MatSnackBarModule providers: [...], // MatSnackBar会由模块自动提供,不需要手动加在这里 bootstrap: [...], entryComponents: [...] }) export class AppModule { }
在组件中使用的示例
当模块配置正确后,你可以在组件中注入MatSnackBar,并使用MatSnackBarConfig来定制通知样式:
import { Component } from '@angular/core'; import { MatSnackBar, MatSnackBarConfig } from '@angular/material'; @Component({ selector: 'app-your-component', template: `...` }) export class YourComponent { constructor(private snackBar: MatSnackBar) {} showCompletionNotification() { const config = new MatSnackBarConfig(); config.duration = 3000; // 通知显示3秒 config.panelClass = ['success-snackbar']; // 自定义样式类 this.snackBar.open('事件已完成!', '关闭', config); } }
版本匹配确认
你的依赖版本是完全兼容的:Angular 5.1.0对应Angular Material 5.0.0,这个版本组合是稳定可用的,不需要升级或降级任何包。
内容的提问来源于stack exchange,提问作者Nagendra Varma
相关产品推荐
相关产品推荐

