【问题标题】:Angular Material Snackbar positionAngular Material Snackbar 位置
【发布时间】:2020-10-26 16:20:39
【问题描述】:

我想在我的标题下放置材料小吃栏(它的高度是 60px)。

问题是verticalPosition 将snackbar 放在顶部并覆盖标题。 我试图添加“margin-top:75px”,但上面的区域是不可点击的。 (有一个覆盖)

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

【问题讨论】:

  • 在 CSS 中使用 !important 和 margin-top 应该会有所帮助。您能否生成您的代码的最小副本,以便我们更容易调试。

标签: css angular angular-material snackbar


【解决方案1】:

你可以试试这个:

  1. 创建一个全局css 类来修改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'
});

【讨论】:

    【解决方案2】:

    来自 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;
    }
    

    【讨论】:

    • 问题是我想把它放在比顶部低一点
    • 如果你使用“margin-top”,你没有机会点击通知上方的区域,因为有一个覆盖
    • 通过我的示例,您可以添加任何适合您需要的 CSS。但总的来说,添加全局样式来解决角度视图封装并不是一个好习惯。因此,如果您需要一些特殊的行为,通常最好编写自己的组件。
    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 2019-10-16
    • 2019-04-16
    • 2018-07-03
    • 1970-01-01
    • 2020-07-15
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多