Angular Material 16如何修改MatCheckbox边框及选中状态颜色
自定义MatCheckbox选中/未选中样式(Angular Material 16)
步骤1:给MatCheckbox添加自定义类
先给你的mat-checkbox加上专属类名(比如custom-checkbox),精准定位样式避免影响其他组件:
<mat-checkbox class="example-margin custom-checkbox" color="primary" [(ngModel)]="selectWorkers[i].isSelected" (change)="onChange($event, worker)"> <span class="worker-name">{{ worker.WorkerName}}</span> <span [ngClass]="isDarkMode?'worker-namedmode':'worker-namelmode'">({{worker.WorkeruserID}})</span> </mat-checkbox>
步骤2:编写自定义样式
根据需求覆盖Angular Material默认样式,有两种实现方式:
方式一:组件内样式(仅作用当前组件)
在组件的.scss文件中添加代码,用:host ::ng-deep穿透样式封装:
:host ::ng-deep .custom-checkbox { /* 未选中状态:边框设为白色 */ .mat-checkbox-frame { border-color: white !important; } /* 选中状态:背景设为绿色 */ &.mat-checkbox-checked .mat-checkbox-background { background-color: green !important; } /* 选中状态:对勾颜色(默认白色,如需绿色则改为green) */ &.mat-checkbox-checked .mat-checkbox-checkmark-path { stroke: white !important; } }
方式二:全局样式(作用整个项目)
在项目根目录的styles.scss中添加代码,无需穿透封装:
.custom-checkbox { /* 未选中状态:边框白色 */ .mat-checkbox-frame { border-color: white; } /* 选中状态:背景绿色 */ &.mat-checkbox-checked .mat-checkbox-background { background-color: green; } /* 选中状态:对勾颜色(按需调整) */ &.mat-checkbox-checked .mat-checkbox-checkmark-path { stroke: white; } }
注意事项
- 使用
!important是为了覆盖Angular Material的默认高优先级样式,也可以通过增加选择器层级(比如加上父组件类名)来提高优先级。 - 如果不需要原生
primary主题颜色,可以直接去掉mat-checkbox上的color="primary"属性。
内容的提问来源于stack exchange,提问作者Anji
相关产品推荐
相关产品推荐

