使用颜色选择器设置角度材质主题颜色

ufo*_*ttu 2 customization themes color-picker angular-material angular

我有一个应用程序,文件中有多个材质主题theme.scss

// Light theme
$light-primary: mat-palette($mat-grey, 200, 500, 300);
$light-accent: mat-palette($mat-brown, 100);
$light-warn: mat-palette($mat-deep-orange, 200);

$light-theme: mat-light-theme($light-primary, $light-accent, $light-warn);

.light-theme {
  @include angular-material-theme($light-theme)
}

// Red theme
$red-primary: mat-palette($mat-red, 700, 500, 300);
$red-accent: mat-palette($mat-amber, 200);
$red-warn: mat-palette($mat-brown, 200);

$red-theme: mat-light-theme($red-primary, $red-accent, $red-warn);

.red-theme {
  @include angular-material-theme($red-theme)
}
Run Code Online (Sandbox Code Playgroud)

如果我想更改应用程序的主题,我可以通过切换现有主题来实现。现在我想添加一个功能,让用户使用颜色选择器创建自定义主题,在应用程序中设置 $primary、$accent 和 $warn 颜色,然后在数据库中发布新创建的样式。

我正在使用ngx-color-picker设置颜色,但我不知道如何设置自定义主题并在用户访问时使用它。

我正在使用 Angular 6 和材质 2

感谢帮助

p4r*_*4r1 6

由于 scss 样式需要编译成 css 才能让浏览器理解,因此动态更改 scss 没有帮助,除非我们即时重新编译样式。虽然这是一个选项,但我认为对于客户端进行样式编译来说,这并不是最高效的。

另一种方法是在编译的主题 css 文件中使用 css 变量,并在运行时更改这些变量的值。为此,您可以使用现有的 theme.scss 文件,但您需要使用 node-sass 将其编译为 css;从命令行运行:

node_modules/.bin/node-sass src/theme.scss -o outputFolder

您还可以使用预构建的 Material css 主题文件之一。打开此 css 文件,并对主要颜色、重音颜色和警告颜色的所有实例执行“查找和替换”操作,以使用 css 变量,例如var(--primary-color), var(--accent-color), var(--warn-color)。除非您碰巧知道要查找的颜色的十六进制值,否则找到这些值可能有点棘手,因此搜索.mat-primary.mat-accent.mat-warn,其中有您要替换整个文件的十六进制值。接下来我们定义在根级别使用的默认主题颜色:

:root {
  --primary-color: purple;
  --accent-color: yellow;
  --warn-color: red;
}
Run Code Online (Sandbox Code Playgroud)

由于我们现在要在主题中使用这个新的 css 文件而不是 scss 文件,因此我们需要替换 angular.json 文件中的 scss 文件以指向新的 css 文件。当您从数据库获取颜色值时,可以使用以下命令将这些变量设置为十六进制值:

document.body.style.setProperty('--primary-color', #someColor);
document.body.style.setProperty('--accent-color', #someColor);
document.body.style.setProperty('--warn-color', #someColor);
Run Code Online (Sandbox Code Playgroud)

这是一个 stackblitz,展示了此工作的简单演示。