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

时间:2019-05-07 06:34:35

标签: angular colors themes

有没有人知道如何在不使用库的情况下将颜色主题应用于angular7 +项目(例如Angular Material或其他)。

我正在为此项目使用SCSS。

我只想更改类名,以更改整个网站的颜色,而不希望切换css文件进行颜色控制。并且将来可以添加更多的颜色主题。

1 个答案:

答案 0 :(得分:0)

我做了类似的事情(但到目前为止只使用了主题文件)。

您无需更改任何样式文件,并且可以将其进一步扩展为更多主题文件(也许可以通过“布局”中的下拉菜单来更改它们)。

首先,我有这样的服务:

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

然后我有一个Layout Component,在其构造函数中,我像这样调用ThemeService:

this.themeService.applyDefaultTheme();

这将在创建布局组件时应用主题文件。可以更改ThemeService以支持更多主题。

theme_default.scss 文件如下所示:

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

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

,然后在其他样式文件中使用这些变量。这样,更改主题文件将更改整个应用程序的颜色。

我希望这会有所帮助。 下次,请尝试在问题上付出更多的努力,因为这样会更容易理解问题是否得到很好回答,并且您会提供已经尝试过的内容。