@nikojpapa's answer 这是更改 Angular Material 组件样式的推荐方法。我将在此处添加更多详细信息。
Slider Toggle 组件有一个名为 color 的属性,它需要一个 ThemePalette 值。可能的 ThemePalette 值为“primary”、“accent”和“warn”。这些与主题的主要、重音和警告调色板变体有关。该组件的颜色属性默认为'accent'。
因此,要自定义颜色,我们需要提供一个调色板作为主题的重点。
假设我们只想更改滑块组件的样式。
为此:
- 我们需要定义一个适合我们需求的新调色板。
- 我们需要创建一个新主题,传递我们的调色板作为滑块切换组件使用的变体(如果滑块切换颜色是“主要”,我们需要使用我们的调色板创建主题作为主要变体)。
- 我们需要将滑块切换的主题更改为我们新定义的主题。
我们在 Angular 应用的 styles.scss 文件中执行所有这些步骤。
例子:
/* styles.scss */
/* required set-up */
@import '~@angular/material/theming';
@include mat-core();
/** 1. Define new color palette. */
$md-custom-toggle-colors: (
50 : #e8f6e9,
100 : #c5e9c8,
200 : #9fdaa4,
300 : #79cb7f,
400 : #5cc063,
500 : #3fb548,
600 : #39ae41,
700 : #31a538,
800 : #299d30,
900 : #1b8d21,
A100 : #c6ffc9,
A200 : #93ff98,
A400 : #60ff67,
A700 : #47ff4f,
contrast: (
50 : #000000,
100 : #000000,
200 : #000000,
300 : #000000,
400 : #000000,
500 : #000000,
600 : #ffffff,
700 : #ffffff,
800 : #ffffff,
900 : #ffffff,
A100 : #000000,
A200 : #000000,
A400 : #000000,
A700 : #000000,
)
);
/**
2. Create new theme, passing above palette as the required variant.
Since the default variant of the Slider Toggle is 'accent', we will pass the above palette as such.
*/
$custom-toggle-theme: mat-light-theme(mat-palette($mat-red), mat-palette($md-custom-toggle-colors));
/** 3. Set new theme as slider toggle theme. */
@include mat-slide-toggle-theme($custom-toggle-theme);
确保将此styles.scss 文件包含在angular.json 文件的样式数组中。请注意,样式文件的顺序在这里很重要 - 后面的文件替换前面文件中定义的样式。
您可能已经在数组中包含了一个预构建的 Angular Material 样式文件。要应用我们新定义的样式,样式数组应如下所示:
{
"projects" : {
"architect": {
"build": {
"styles" : [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"./src/styles.scss"
]
}
}
}
}