来自 api 文档 (https://material.angular.io/components/snack-bar/api):
MatSnackBar 的“Open”方法参数:
message (string) - The message to show in the snackbar.
action (string) - The label for the snackbar action.
config? (MatSnackBarConfig<any>) - Additional configuration options for the snackbar.
MatSnackBarConfig 具有以下属性:
horizontalPosition: MatSnackBarHorizontalPosition - The horizontal position to place the snack bar.
verticalPosition: MatSnackBarVerticalPosition - The vertical position to place the snack bar.
要查看实际效果,您可以轻松创建一个组件,注入 MatSnackBar 和
编写一个 open 方法来传递您的配置。
下面是我的 Snackbar 组件的一个小例子:
import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-mat-snackbar',
templateUrl: './mat-snackbar.component.html',
styleUrls: ['./mat-snackbar.component.scss']
})
export class MatSnackbarComponent {
constructor(public snackBar: MatSnackBar) {}
openSnackBar(message: string, action: string, className: string) {
this.snackBar.open(message, action, {
duration: 9000,
verticalPosition: 'top',
horizontalPosition: 'center',
panelClass: [className],
});
}
}
我这样从我的 http 拦截器中调用它:
constructor(private SnackbarComponent: MatSnackbarComponent) {}
...
...
// Something wrong happened
this.SnackbarComponent.openSnackBar(errorMessage, 'Close', 'error-snackbar');
在我的 Style.css 文件中,我为这个快餐栏添加了一个 css 类,它也是 openSnackBar 方法的最后一个参数。
这只是一种解决方法,因为我的 mat-snackbar.component.css 中的某些 css 不起作用。我在这里找到了::ng-deep 的其他解决方案:MatSnackBar panelClass doesnt read styling class。
你必须小心使用它,因为如果你使用styles.css中的样式,没有ViewEncapsulation。但对我来说,这样做更干净。
我的 styles.css 看起来像:
.error-snackbar {
position: absolute;
top: 60px;
}