You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在选中行复选框后修改Angular Material表头复选框颜色

实现Angular Material表格表头复选框颜色随行选择变化

步骤1:给表头复选框绑定动态样式类

修改现有模板中表头的<mat-checkbox>,通过[ngClass]根据选中状态添加自定义样式类:

<ng-container matColumnDef="select">
    <th mat-header-cell *matHeaderCellDef>
        <mat-checkbox 
            (change)="$event ? masterToggle() : null" 
            [checked]="selection.hasValue() && isAllSelected()"
            [indeterminate]="selection.hasValue() && !isAllSelected()"
            [ngClass]="{'header-checkbox-active': selection.hasValue()}">
        </mat-checkbox>
    </th>
    <td mat-cell *matCellDef="let row">
        <mat-checkbox 
            (click)="$event.stopPropagation()" 
            (change)="$event ? selection.toggle(row) : null"
            [checked]="selection.isSelected(row)">
        </mat-checkbox>
    </td>
</ng-container>

<ng-container matColumnDef="bcNumber">
    <th mat-header-cell *matHeaderCellDef> BC # </th>
    <td mat-cell *matCellDef="let element">
        {{element.bcNumber}}
    </td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

步骤2:添加自定义CSS样式

在组件样式文件(.scss/.css)中,针对自定义类修改复选框颜色:

/* 修改选中/半选中状态的背景色 */
.header-checkbox-active .mat-checkbox-checked .mat-checkbox-background,
.header-checkbox-active .mat-checkbox-indeterminate .mat-checkbox-background {
    background-color: #2196F3; /* 替换为你需要的颜色 */
}

/* 可选:修改未选中时的边框颜色 */
.header-checkbox-active .mat-checkbox-frame {
    border-color: #1976D2;
}

逻辑说明

通过selection.hasValue()判断表格是否有选中行,动态为表头复选框添加样式类,再利用Angular Material内置的复选框状态类,精准修改对应状态下的颜色,实现需求。

内容的提问来源于stack exchange,提问作者Awanish Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 07:22:17