Angular Material 小吃店位置

Angular Material Snackbar position

我想在我的 header 下放置 material 小吃店(它的高度是 60px)。

问题在于 verticalPosition 将 snackbar 置于顶部并覆盖 header。 我尝试添加“margin-top: 75px”,但上面的区域无法点击。 (有叠加层)

我无法更改 cdk-overlay-pan 的样式,因为我还有其他对话框。

你可以试试这个:

  1. 创建全局 css class 以修改 Snackbar 组件的样式。
  2. 在配置选项中设置 panelClass 属性。

在全局中添加此样式声明 styles.scss :

.my-custom-snackbar {
  margin: 0 !important;
  position: absolute;
  right: 25px;
  top: 60px;
}

然后当SnackBar打开时:

this.snackbar.open('Hello the world!', '', {
  panelClass: 'my-custom-snackbar'
});

来自 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 文件中,我为这个 snackbar 添加了一个 css class,这也是 openSnackBar 方法的最后一个参数。 这只是一种解决方法,因为我的 mat-snackbar.component.css 中的某些 css 不起作用。我在这里找到了 ::ng-deep 的其他解决方案:。 使用styles.css中的style是没有ViewEncapsulation的,需要谨慎使用。但对我来说,这样做更干净。

我的 styles.css 看起来像:

.error-snackbar {
  position: absolute;
  top: 60px;
}

您需要将 margin-top 应用到 snack-bar-container 元素的父元素 div。 使用此 CSS(根据您的结构,您可能需要为 View.Encapsulation 应用 none。)

.mat-snack-bar-handset {
    margin-top: 75px !important; 
}