Angular Material 使用颜色选择器设置主题颜色

标签 angular angular-material themes customization color-picker

我在 theme.scss 文件中有一个包含多个 Material 主题的应用:

// 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)
}

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

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

我正在使用 Angular 6 和 Material 2

感谢帮助

最佳答案

由于 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;
}

由于我们现在要为我们的主题使用这个新的 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);

Here's a stackblitz显示此工作的简单演示。

关于Angular Material 使用颜色选择器设置主题颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53005796/

相关文章:

php - 在没有 Web 界面的情况下在 Drupal 中切换主题

javascript - 如何在Angular 5应用程序中从Gmail API获取authorization_code

javascript - 将脚本应用于 Angular 2 上的输入

forms - 如何以编程方式将焦点设置为在 Angular2 中动态创建的 FormControl

Angular 未捕获类型错误 : e is not a constructor after build --prod (work on ng serve)

带有 mat-autocomplete 和输入组合的 Angular mat-chips,从列表中选择时添加一个额外的芯片

angular - 如何在 Angular Material 下拉 Angular 5中实现全选

Angular MatTab : Remember Selected Tab

views - Drupal 7 Views - 自定义 RSS 输出模板

php - 如何将多个可重复字段保存为数据库中的数组?