Angular Material - 更改所选 mat-list-option 的颜色

Tan*_*mar 10 angular-material angular2-template angular-material2 angular2-material angular

如何更改所选选项的颜色mat-list-option?现在我有这样的事情:

当前列表 在此处输入图片说明

我想将整个选项或卡片“选择时”的颜色更改为绿色。像这样的东西:在此处输入图片说明

我的代码是这样的:

<mat-selection-list #list>
    <mat-list-option *ngFor="let yuvak of yuvaks">
    {yuvak.name}
    {yuvak.phonenumber}
     </mat-list-option>
</mat-selection-list>
Run Code Online (Sandbox Code Playgroud)

Abh*_*mar 16

您可以使用标签中的aria-selected="true"属性mat-list-option来定位所选选项,
并为其提供相应的 css 属性。

mat-list-option[aria-selected="true"] {
  background: rgba(0, 139, 139, 0.7);
}
Run Code Online (Sandbox Code Playgroud)

Stackblitz 工作演示


Mai*_*jat 7

落下:

当选项处于活动状态以及选择选项时会mat-list-option触发。根据您的需要,将以下内容添加到您的 CSS 中以修改活动或选定的样式。mat-option.mat-activemat-option.mat-selected

.mat-option.mat-active {
  background: blue !important;
}

.mat-option.mat-selected {
  background: red !important;
}
Run Code Online (Sandbox Code Playgroud)

工作演示

选型清单:

选择列表有aria-selected属性,默认为falsetrue如果您选择该项目,它会更改为。您所需要的只是设置 CSS,如下所示:

.mat-list-option[aria-selected="true"] {
  background: rgba(200, 210, 90, 0.7);
}
Run Code Online (Sandbox Code Playgroud)

工作演示


and*_*tor 5

The accepted answer works fine, but it uses a hardcoded color value (background: rgba(0, 139, 139, 0.7)). This approach will actually break your styles and colors if you decide to switch to another pre-build material theme or use a custom theme (as described in Theming your Angular Material app page).

So, if you use SCSS, you can use the following code in your component's style file:

@import '~@angular/material/theming';

mat-list-option[aria-selected="true"] {
  background: mat-color($mat-light-theme-background, hover, 0.12);
}
Run Code Online (Sandbox Code Playgroud)

The above code is adapted from mat-select options - in this way, you will have a consistent look in the entire app: .mat-option.mat-selected:not(.mat-option-multiple) { background: mat-color($background, hover, 0.12);}

Demo: https://stackblitz.com/edit/material-selection-list-5-0-0-selection-color-change-qaq1xr

Or, if you use a dark theme, change code as follows:

mat-list-option[aria-selected="true"] {
  background: mat-color($mat-dark-theme-background, hover, 0.12);
}
Run Code Online (Sandbox Code Playgroud)

Demo: https://stackblitz.com/edit/material-selection-list-5-0-0-selection-color-change-w8beng

If you just want to use a custom color, I suggest to pick one from Material Specs, that are also exposed in Angular Material Design scss.

$primaryPalette: mat-palette($mat-green);

mat-list-option[aria-selected="true"] {
  background: mat-color($primaryPalette, 500);
}
Run Code Online (Sandbox Code Playgroud)

Demo: https://stackblitz.com/edit/material-selection-list-5-0-0-selection-color-change-tt3nyj