简体   繁体   English

为 Angular Material 和自定义组件提供具有自定义颜色的多个主题

[英]Having multiple themes with custom colors for Angular Material and custom components

I'd like to have a few themes in my app, but along with Angular Material themes I also want to define custom colors that are used by specific components and elements that aren't part of Angular Material.我想在我的应用程序中有一些主题,但除了 Angular Material 主题外,我还想定义由不属于 Angular Material 的特定组件和元素使用的自定义颜色。 Whenever I change a theme those custom colors should be changed as well.每当我更改主题时,这些自定义颜色也应该更改。 Let's say I have a file that defines colors for each theme, then I'd like to import it in an arbitrary scss file and utilize the colors to style some elements假设我有一个为每个主题定义颜色的文件,然后我想将它导入到任意 scss 文件中并利用这些颜色来设置一些元素的样式

@import "custom-colors"

.my-elem {
 color: $textColor;
}

Then, if I need to change a theme I would apply a specific class to the outer most container of the app, and after this I'd like $textColor to have another value, so that color of the .my-elem would change.然后,如果我需要更改主题,我会将特定类应用于应用程序的最外层容器,然后我希望$textColor具有另一个值,以便.my-elem color会改变。

Is there any way of doing this without writing something like有没有办法做到这一点而不写类似的东西

.another-theme {
 .my-elem {
   color: $textColorOfAnotherTheme;
 }
}

In every component that should be affected by theme changing?在每个应该受主题更改影响的组件中?

There are 2 ways to change themes两种方法可以更改主题
1. Adding parent class to your root component 1. 将父类添加到您的根组件
2. Changing file name (As angular material done) 2. 更改文件名(作为角材料完成)

1. You can add css with parent class (Example below) 1.你可以添加带有父类的css(下面的例子)

.light {
 mat-form-field {
  color: white;
 }
 my-custom-element {
 color: white;
 }
}
.dark {
 mat-form-field {
  color: black;
 }
 my-custom-element {
  color: black;
 }
}

and when user change theme, you can change class on your root element <app-component class="light">当用户更改主题时,您可以更改根元素上的类<app-component class="light">

There are various ways to do it: Having global varible , Using Event Emitter有多种方法可以做到:拥有全局变量使用事件发射器

2. Changing file names, same file without parent class will be divided into light.css and dark.css 2.更改文件名,同一个没有父类的文件会被分成light.cssdark.css

and upon user changing theme, you can replace <link ref="stylesheet" href="light.css">并且在用户更改主题时,您可以替换<link ref="stylesheet" href="light.css">

Angular way of doing this is, using Rendere 2 Set Attribute Angular 的做法是,使用Rendere 2 Set Attribute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM