角材料-更改所选的垫子列表选项的颜色

时间:2018-11-22 23:09:11

标签: angular angular-material angular2-template angular-material2 angular2-material

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

当前列表 enter image description here

我想将整个选项或“选择时”卡片的颜色更改为绿色。像这样的东西:enter image description here

我的代码是这样的:

<mat-selection-list #list>
    <mat-list-option *ngFor="let yuvak of yuvaks">
    {yuvak.name}
    {yuvak.phonenumber}
     </mat-list-option>
</mat-selection-list>

4 个答案:

答案 0 :(得分:3)

可接受的答案很好用,但是它使用了硬编码的颜色值background: rgba(0, 139, 139, 0.7))。 如果您决定切换到另一个预构建的材质主题或使用自定义主题(如Theming your Angular Material app页中所述),这种方法实际上会破坏您的样式和颜色。

因此,如果您使用SCSS,则可以在组件的样式文件中使用以下代码:

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

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

以上代码改编自 mat-select options -通过这种方式,您将在整个应用程序中拥有一致的外观: .mat-option.mat-selected:not(.mat-option-multiple) { background: mat-color($background, hover, 0.12);}

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

或者,如果您使用深色主题,请按如下所示更改代码:

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

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

如果您只想使用自定义颜色,建议您从Material Specs中选择一种,该颜色也将在Angular Material Design scss中公开。

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

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

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

答案 1 :(得分:2)

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

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

Stackblitz Working Demo

答案 2 :(得分:0)

下拉:

mat-list-option具有mat-option.mat-active,它在选项处于活动状态时触发,在mat-option.mat-selected被选中时触发。根据需要,将以下内容添加到CSS中以修改活动或选定的样式。

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

.mat-option.mat-selected {
  background: red !important;
}

工作Demo

选择列表:

选择列表具有aria-selected属性,默认情况下为false。如果选择该项,它将变为true。您只需要将CSS设置如下:

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

工作Demo

答案 3 :(得分:0)

有时使用 [aria-selected] 似乎太“迟钝”了。

您还可以获取节点的选定状态并根据需要使用它。

示例 1:您有一个子组件需要将状态传递给

<mat-list-option #option>

   <app-custom-list-option-widget [selected]="option.selected"></app-custom-list-option-widget>

</mat-list-option>

示例 2:您想设置自定义 css 类而不是使用 [aria-selected]

.is-selected { color: red; }

然后在模板中:

<mat-list-option #option>

   <span [class.is-selected]="option.selected"> Option text </span>

</mat-list-option>
相关问题