在angular2中实现主题

Implementing theme in angular2

我正在尝试在 Angular2 项目中实现主题。

当有人更改网络应用程序的主题时,它会使用 javascript 更改正文的 class。应用程序中的每个组件都有与每个主题相关的颜色。

有人可以建议我如何在 Angular2 组件中执行此操作。

当我使用

编写组件样式表时
body.theme-1 .header {
   background-color: red;
}

没用。

任何其他实现方式。

如果我从组件样式表中剪切相同的 css 并放入 index.html 或通用样式表中,它就可以工作。但它是一个巨大的应用程序,我不想将所有组件样式都写到一个地方。无法管理。

如果您在组件中声明 ViewEncapsulation.none,该组件的样式将全局应用于您的应用程序。

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'style-test',
  template: `<div> Global stylesheet</div>`,
  styles: ['body {
                  background: blue;
                 }'],
  encapsulation: ViewEncapsulation.None // Use to 
                                       //disable CSS 
                                      //Encapsulation 
                                     //for this component
})
export class SecondComponent {
  constructor() { }
}

我从 Angular2 文档中找到了答案。

您可以使用 :host-context() 函数

:host-context(.theme-1) .header {
    background-color: red;
}

它就像一个魅力。

https://angular.io/docs/ts/latest/guide/component-styles.html

查看上方 link 了解更多信息