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

Angular中mat-slide-toggle颜色修改无效,求实现绿红切换效果

解决Angular mat-slide-toggle颜色无法自定义的问题

问题分析

你添加::ng-deep样式后,mat-slide-toggle仍显示默认粉色,核心原因有两个:

  • 选择器优先级不足,被Material主题的默认样式覆盖
  • 仅定义了激活状态样式,未处理未激活状态的样式规则

解决方案

方案一:增强选择器优先级+补充完整状态样式

给mat-slide-toggle添加自定义类提升样式优先级,同时补全未激活状态的样式:

HTML代码

<td data-label="Actief" *ngIf="user.enabled">
    <mat-slide-toggle class="custom-slide-toggle"></mat-slide-toggle>
</td>

CSS代码(组件内样式文件)

/* 激活状态:滑块与轨道颜色 */
::ng-deep .custom-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb {
    background-color: rgb(50, 170, 118);
}

::ng-deep .custom-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar {
    background-color: rgb(113, 226, 147);
}

/* 未激活状态:滑块与轨道颜色 */
::ng-deep .custom-slide-toggle:not(.mat-checked):not(.mat-disabled) .mat-slide-toggle-thumb {
    background-color: rgb(220, 53, 69);
}

::ng-deep .custom-slide-toggle:not(.mat-checked):not(.mat-disabled) .mat-slide-toggle-bar {
    background-color: rgb(255, 182, 193);
}

方案二:全局样式定义(推荐)

若不想使用::ng-deep,可在项目根目录的styles.scss(或styles.css)中直接添加样式,无需额外前缀:

/* 激活状态 */
.custom-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb {
    background-color: rgb(50, 170, 118);
}

.custom-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar {
    background-color: rgb(113, 226, 147);
}

/* 未激活状态 */
.custom-slide-toggle:not(.mat-checked):not(.mat-disabled) .mat-slide-toggle-thumb {
    background-color: rgb(220, 53, 69);
}

.custom-slide-toggle:not(.mat-checked):not(.mat-disabled) .mat-slide-toggle-bar {
    background-color: rgb(255, 182, 193);
}

方案三:关闭组件视图封装

在组件的TS文件中关闭视图封装,使组件内样式全局生效,无需::ng-deep:

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'your-component-selector',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class YourComponent {
  // 组件逻辑
}

组件内CSS可直接编写:

/* 激活状态 */
.mat-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb {
    background-color: rgb(50, 170, 118);
}

.mat-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar {
    background-color: rgb(113, 226, 147);
}

/* 未激活状态 */
.mat-slide-toggle:not(.mat-checked):not(.mat-disabled) .mat-slide-toggle-thumb {
    background-color: rgb(220, 53, 69);
}

.mat-slide-toggle:not(.mat-checked):not(.mat-disabled) .mat-slide-toggle-bar {
    background-color: rgb(255, 182, 193);
}

注意事项

  • ::ng-deep在Angular 12+已标记为废弃,长期来看推荐使用全局样式或关闭视图封装的方案
  • 若样式仍不生效,可临时在颜色值后添加!important(仅应急使用,会增加样式维护难度)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:25:18