Angular 8 材料表在单击时突出显示一行,并在单击另一行后保留背景颜色



我在单击另一行后寻找一种简单的方法来保存一行的颜色

我的垫子行

<tr mat-row *matRowDef="let row; columns: ['favicon', 'name', 'quality', 'created_at', 'report', 'edit']" 
(click)="selectedRow = selectedRow === row ? null : row" [ngClass]="{ 'selected': row === selectedRow }"> 

.ts

selectedRow

.css

.selected {
background-color: red!important;
}
.mat-row:nth-child(even){
background-color: #e4f0ec;
}
.mat-row:nth-child(odd){
background-color:#ffffff;
}

问题:单击某些行后,背景变为红色 (这没关系(但是单击其他行后,预览(红色(行丢失了背景颜色。

预期成果: 所有单击的行都需要保存红色,或者更好的是 - 获取其他颜色(以区别 - 行 - 所选行 - 访问的行(。

Ivan,你不能使用唯一变量,你需要使用数组或元素的新属性。想象一下,你称这个新的变奏曲为"选定">

<tr mat-row *matRowDef="let element; columns: columnsToDisplay;"
[class.selected]="element.selected"
(click)="element.selected= !element.selected">
</tr>

看到你的"元素"可以具有表中未显示的属性

角度材质组件的问题 它们被包装在许多样式类中,很难覆盖它。尽管我发现了一些解决方案如何覆盖mat-*样式。我给你举个例子:

1. 在全局样式.css文件中定义样式类

首先,您需要发现哪些类用于您的操作。它可以通过谷歌浏览器中的开发工具或其他工具来完成。
然后在全局样式文件(style.cssstyle.scss...(中定义该类样式。
(我的情况(:

.mat-focused .mat-form-field-label, .mat-datepicker-toggle {
color: white !important;
} 

2. 使用 ::ng-deep 或>>> 定义样式类

(已弃用(
在组件样式类中,使用::ng-deep>>>前缀定义相同的发现mat-*样式类。
(我的情况(:

::ng-deep .mat-focused .mat-form-field-label, .mat-datepicker-toggle {
color: white !important;
}

尽管此解决方案已弃用,并且我没有找到替代它以覆盖组件样式文件中的样式。


3. 使用不带视图封装的自定义样式类

首先,您需要在组件中设置封装参数/标志。例:

@Component({
selector: 'app-my-element',
templateUrl: './my-element.component.html',
styleUrls: ['./my-element.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class MyElementComponent implements OnInit {
...
}

然后,您可以为角度材质组件编写自己的样式类。 可能是材质组件看起来不像以前那样(真正的材质组件(


这不是您问题的确切解决方案,而是找到自己解决方案的方向

最新更新