MatSnackBar panelClass 不读取样式类

问题描述 投票:0回答:5

我想在MatSnackBar panelClass中插入一个scss类。但它不起作用。仅供参考,verticalPosition 和horizontalPosition 工作正常。这是我的 TS:

 openSnackBar(message: string, action: any) {
    this.snackBar.open(message, action, {
      duration: 2000,
      verticalPosition: 'top',
      horizontalPosition: 'center',
      panelClass: ['alert-red'],
    });
 } 

这是我的 Scss:

.alert-red{
  padding: 20px;
  background-color: red;
  color: white;
}
angular typescript angular-material
5个回答
10
投票

编辑: 如果您在班级中添加以下

::ng-deep snack-bar-container
前缀(请参阅 this 评论),它似乎可以工作。所以你的组件 SCSS 文件应该如下所示:

::ng-deep snack-bar-container.alert-red{
  padding: 20px;
  background-color: red;
  color: white;
}

解决方法:参见帖子here,似乎您需要将样式放在应用程序

styles.scss
文件中,而不是组件SCSS文件中。

检查this stackblitz,该样式在

styles.scss
中有效,但当您将其注释掉并将其留在
app.component.scss
中时则无效。不确定这是否是错误或预期行为。


2
投票

您必须为组件设置

encapsulation
属性:

喜欢:

import { ViewEncapsulation } from '@angular/core'; // import ViewEncapsulation from core

@Component({
  encapsulation: ViewEncapsulation.None  // Set ViewEncapsulation.None for encapsulation property
})

并在 HTML 文件中添加 CSS 类:

this.snackBar.open("message", {
      panelClass:['customClass']
});

在 CSS 文件中:

.customClass{
  color: red;
}

工作演示


1
投票

我遇到了同样的问题,我只是在 css 类中定义的属性之后添加 !important 以覆盖一些默认样式。所以喜欢:

    .alert-red{
      padding: 20px !important;
      background-color: red !important;
      color: white !important;
    }

1
投票
    $snackBarContainerColorError: #d32f2f;
$snackBarContainerColorSuccess: #43a047;

mat-snack-bar-container.success {
  .mdc-snackbar__surface {
    background-color: $snackBarContainerColorSuccess !important;
  }
}


mat-snack-bar-container.error {
  .mdc-snackbar__surface {
    background-color: $snackBarContainerColorError !important;
  }
}

此功能适用于 16.0.4


0
投票

我今天遇到了同样的错误,我通过使用 styles.sccs 中的这些特定类解决了它:

.mat-mdc-snack-bar-container {
  &.success-snackbar {
    --mdc-snackbar-container-color: green;
  }
}

.mat-mdc-snack-bar-container {
  &.error-snackbar {
    --mdc-snackbar-container-color: red;
  }
}

在面板中我使用了snackbar-success 或snackbar-error。

© www.soinside.com 2019 - 2024. All rights reserved.