如何自定义Angular-Material的mat-slide-toggle组件的颜色、高度与宽度
Hey there! Let's break down how to customize your Angular Material mat-slide-toggle—covering color, height, and width adjustments. Here's step-by-step what you need to do:
Customizing the Toggle Color
You have two main options here: using Angular Material's built-in theme colors, or defining completely custom hues.
Using Built-in Theme Colors
Angular Material comes with preset color palettes (primary, accent, warn) tied to your app's theme. Just pass one of these values to the color input directly:
<mat-slide-toggle [color]="'primary'" [checked]="checked" [disabled]="disabled"></mat-slide-toggle>
Swap 'primary' with 'accent' or 'warn' to use those theme colors instead.
Defining Custom Colors
If you want a unique color (like a specific hex code), you'll need to target the toggle's internal elements with CSS. Since Angular uses view encapsulation, use ::ng-deep (paired with :host to limit scope to your component) or add styles to your global styles.scss file. Here's an example:
/* In your component's .scss file */ :host ::ng-deep .custom-color-toggle { /* Unchecked track color */ .mat-slide-toggle-bar { background-color: #d1d5db; } /* Unchecked thumb color */ .mat-slide-toggle-thumb { background-color: #9ca3af; } /* Checked state styles */ &.mat-slide-toggle-checked { .mat-slide-toggle-bar { background-color: #10b981; } .mat-slide-toggle-thumb { background-color: #059669; } } /* Disabled state styles */ &.mat-slide-toggle-disabled { .mat-slide-toggle-bar { background-color: #e5e7eb; } .mat-slide-toggle-thumb { background-color: #d1d5db; } } }
Then add the custom class to your component:
<mat-slide-toggle class="custom-color-toggle" [checked]="checked" [disabled]="disabled"></mat-slide-toggle>
Adjusting Height & Width
The toggle's size is controlled by its track (the bar) and thumb (the circle). Target these elements with CSS to resize them:
/* In your component's .scss file */ :host ::ng-deep .custom-size-toggle { /* Resize the track */ .mat-slide-toggle-bar { width: 64px; /* Default is ~48px */ height: 28px; /* Default is ~24px */ } /* Resize the thumb and adjust its position */ .mat-slide-toggle-thumb { width: 24px; /* Default is ~20px */ height: 24px; } /* Make sure the thumb aligns correctly when checked */ &.mat-slide-toggle-checked .mat-slide-toggle-thumb { transform: translateX(calc(64px - 24px)); } }
Apply the class to your toggle:
<mat-slide-toggle class="custom-size-toggle" [color]="color" [checked]="checked" [disabled]="disabled"></mat-slide-toggle>
Quick Notes to Avoid Issues
- Using
:host ::ng-deepensures your styles only affect toggles inside the current component, preventing global style leaks. - If you're using Angular 15+, you can also use
ViewEncapsulation.Noneon your component, but:host ::ng-deepis more targeted. - Test disabled states to make sure your custom styles still look consistent.
内容的提问来源于stack exchange,提问作者Murugan C

