如何自定义Angular Material的mat-checkbox样式实现勾选时显示X而非对勾
方案1:使用 :host + ::ng-deep 限制样式作用域(无需修改视图封装,无全局污染)
该方案是Angular官方推荐的组件内部穿透样式的规范写法,样式只会作用于当前组件内的元素,完全不会影响其他组件的 <mat-checkbox>。
实现步骤:
- 在组件模板中给目标
<mat-checkbox>添加自定义类,同时绑定状态控制类
<!-- 组件模板文件 --> <mat-checkbox class="custom-toggle-checkbox" [class.x-state]="currentState === 'no'" [checked]="currentState !== 'none'" > </mat-checkbox> <button (click)="currentState = 'yes'">Yes</button> <button (click)="currentState = 'no'">No</button>
- 在组件类中声明状态变量
// 组件ts文件 currentState: 'yes' | 'no' | 'none' = 'none';
- 在组件样式文件中添加穿透样式,用
:host限制作用域
/* 组件css文件 */ :host ::ng-deep .custom-toggle-checkbox.x-state .mat-checkbox-checkmark { display: none; /* 隐藏默认对勾 */ } :host ::ng-deep .custom-toggle-checkbox.x-state .mat-checkbox-background { content: url(/assets/icons/cancel_checkbox.svg) !important; /* 也可以用伪元素直接画叉号,无需额外svg资源: &::after { content: '×'; color: #fff; font-size: 18px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } */ }
方案2:全局样式加专属前缀(无需使用::ng-deep)
如果不想用::ng-deep,可以给当前组件的宿主元素添加唯一专属类,再把样式写到全局样式文件中:
- 给当前组件添加宿主类
// 组件ts文件 @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', host: {'class': 'app-your-special-component'} // 加唯一的宿主类 })
- 在全局样式文件中添加限定范围的自定义样式
/* 全局styles.css */ .app-your-special-component .custom-toggle-checkbox.x-state .mat-checkbox-checkmark { display: none; } .app-your-special-component .custom-toggle-checkbox.x-state .mat-checkbox-background { content: url(/assets/icons/cancel_checkbox.svg) !important; }
内容的提问来源于stack exchange,提问作者tiana
相关产品推荐
相关产品推荐

