如何在角度组件中处理多个主题? [英] How can I handle multiple themes in an angular component?

查看:47
本文介绍了如何在角度组件中处理多个主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个 Angular 9 项目,我正在创建两个主题,每个主题都有自己的 css 输出文件.我修改了 angular.json 文件来处理:

I'm working on an Angular 9 project where I'm creating two themes and each theme has it's own css output file. I modified the angular.json file to handle that:

"styles": [
  {
    "input": "src/styles/themes/light-theme.scss",
    "lazy": true,
    "bundleName": "light-theme"
  },
  {
    "input": "src/styles/themes/dark-theme.scss",
    "lazy": false,
    "bundleName": "dark-theme"
  }
],

light-themedark-theme 是我的输入文件,我在其中设置如下变量:

light-theme and dark-theme are my input files, where I'm setting variables like:

  • $background-color
  • $button-color
  • $text-color
  • 等等等等

我的问题是我不能使用每个组件的这些变量,因为我的组件不知道这些变量是什么.我无法导入一个或另一个主题,因为我想使用我在输入文件中声明的值.我该如何处理?有什么方法可以导入"我在 angular.json 文件上写的输入文件?

My problem is that I cannot use those variables from each component, because my component won't know what those variables are. I cannot import one or another theme, because I would like to use the values that I declared in the input file. How should I handle this? Is there any way of "importing" the input file I wrote on my angular.json file?

谢谢!

推荐答案

如果在全局样式中定义了 sass 变量,则在动态更改主题后将无法访问它们.这是因为动态加载的主题将只包含 css 规则,而不包含 sass;除了在运行时,您的组件 scss 也已经编译为 css,因此无论哪种方式都没有更多的 sass 变量概念.

If you define sass variables in your global styles, you won't be able to access them after when you dynamically change the theme. This is because the dynamically loaded theme will contain css rules only, not sass; besides at run time your components scss has also already compiled to css so there is no more notions of sass variables either way.

您可以做的是使用 CSS 变量, 具有良好的浏览器支持(IE 和Opera mini 除外).

What you can do instead is use CSS variables, which have good browser support (apart from IE and opera mini).

例如,您可以在主题文件中定义这些变量

So for instance, you can define these variables in your theme files

dark-theme.scss

:root{
  --button-background: darkgrey;
  --button-color: white;
}

light-theme.scss

:root{
  --button-background: lightgrey;
  --button-color: black;
}

然后在你的组件中,使用这些变量

Then in your component, use these variables

component.scss

button
{
  cursor: pointer;
  padding: 10px;
  border: 0;
  color:var(--button-color);
  background-color:var(--button-background);
}

然后,当您动态加载轻量级主题时,它将覆盖现有变量.如果您随后动态删除 light-theme.css,它将返回使用您的深色主题变量.

Then, when you dynamically load the light theme, it will override the existing variables. If you then dynamically remove light-theme.css, it'll go back to using your dark theme's variables.

这篇关于如何在角度组件中处理多个主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆