简体   繁体   English

不使用库在Angular 7+中创建自定义颜色主题

[英]Creating custom color themes in Angular 7+ not using library

Does anyone knows how to apply color themes to angular7+ project without using library(like Angular Material or others). 有没有人知道如何在不使用库(如Angular Material或其他)的情况下将颜色主题应用于angular7 +项目。

I am using SCSS for this project. 我正在使用SCSS进行此项目。

I want to only changing the class name at to change the whole website color, but not switching the css file for color control. 我想只更改类名来改变整个网站颜色,但不切换css文件进行颜色控制。 And it's able to add more color theme in the future. 并且它能够在未来添加更多颜色主题。

I did something similar (but only with a theme file so far). 我做了类似的事情(但到目前为止只有一个主题文件)。

You don't have to change any style file and you can extend this further for more theme files (maybe change them with a dropdown in your Layout). 您不必更改任何样式文件,您可以进一步扩展它以获得更多主题文件(也许可以通过布局中的下拉菜单更改它们)。

First of all, I have a service like this: 首先,我有这样的服务:

const defaultTheme = require('../styles/themes/theme-default.scss');

@Injectable({
  providedIn: SharedModule
})
export class ThemeService {

  styleTag: any;

  constructor() {
    this._createStyle();
  } 

  applyDefaultTheme(){
    this.injectStylesheet(defaultTheme);
  }

  private _createStyle() {
    const head = document.head || document.getElementsByTagName('head')[0];
    this.styleTag = document.createElement('style');
    this.styleTag.type = 'text/css';
    this.styleTag.id = 'appthemes';
    head.appendChild(this.styleTag);
  }

  injectStylesheet(css) {
    this.styleTag.innerHTML = css;
  }
}

Then I have a Layout Component and in its constructor I call the ThemeService like this: 然后我有一个布局组件,在我的构造函数中,我像这样调用ThemeService:

this.themeService.applyDefaultTheme();

This will apply the theme file as the Layout Component is created. 这将在创建布局组件时应用主题文件。 The ThemeService can be changed to support more themes. 可以更改ThemeService以支持更多主题。

The theme_default.scss file looks something like this: theme_default.scss文件看起来像这样:

////////////////
    // SIDEBAR
    $sidebar-bg : $aside-bg;
    $sidebar-item-color : #FFFFFF;

    body,
    .wrapper .section-container {
      background-color: $content-bg;
    }
////////////////

and I use those variables in other style files. 我在其他样式文件中使用这些变量。 With that, changing the theme file will change the colors all over the app. 有了它,更改主题文件将改变整个应用程序的颜色。

I hope this helps. 我希望这有帮助。 Next time try to put a bit more effort in your question, as it is easier to understand if it is well asked and you provide what you already tried. 下一次尝试在您的问题中付出更多努力,因为如果问得好并且您提供了您已经尝试过的内容,则更容易理解。

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

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