【问题标题】:Implementing theme in angular2在angular2中实现主题
【发布时间】:2016-11-06 17:28:08
【问题描述】:

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

当有人更改 web 应用程序的主题时,它会使用 javascript 更改 body 的类。并且应用程序中的每个组件都有与每个主题相关的颜色。

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

当我用

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

它不起作用。

任何其他方式来实现这一点。

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

【问题讨论】:

    标签: css angular styles less components


    【解决方案1】:

    如果您在组件中声明 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() { }
    }
    

    【讨论】:

    • 感谢@JS_astronauts,这可行,但它松散了组件封装。我使用了 :host-context() (angular.io/docs/ts/latest/guide/component-styles.html)。您仍然可以进行封装
    • 如果直接在 index.html 中添加 CSS,则不需要禁用视图封装。这样的样式不会被 Angular2 重写,而是应用于页面中的所有元素(除非ViewEncapsulation.Native 用于支持原生 shadow DOM 的浏览器中)
    【解决方案2】:

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

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

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

    它就像一个魅力。

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

    查看以上链接了解更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-03
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多