Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Css 用angular2实现主题_Css_Angular_Styles_Less_Components - Fatal编程技术网

Css 用angular2实现主题

Css 用angular2实现主题,css,angular,styles,less,components,Css,Angular,Styles,Less,Components,我试图在Angular2项目中实现主题化 当有人更改web应用程序的主题时,它将使用javascript更改主体的类。应用程序中的每个组件都有与每个主题相关的颜色 有人能建议我如何在Angular2组件中执行此操作吗 当我用 body.theme-1 .header { background-color: red; } 它不起作用 任何其他实现这一点的方法 如果我从组件样式表中剪切相同的css并放入index.html或common样式表中,它就会工作。但它是一个巨大的应用程序,我不想把

我试图在Angular2项目中实现主题化

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

有人能建议我如何在Angular2组件中执行此操作吗

当我用

body.theme-1 .header {
   background-color: red;
}
它不起作用

任何其他实现这一点的方法


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

如果您在组件中声明
视图封装。无
,则该组件中的样式将全局应用于您的应用程序

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() { }
}
从'@angular/core'导入{Component,ViewEncapsulation};
@组成部分({
选择器:“样式测试”,
模板:`Global stylesheet`,
样式:[正文]{
背景:蓝色;
}'],
封装:视图封装。无//用于
//禁用CSS
//封装
//对于此组件
})
导出类第二组件{
构造函数(){}
}

我从Angular2文档中找到了答案

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

它就像一个符咒


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

谢谢@JS_宇航员,这可以正常工作,但会导致组件封装松动。我使用了:host-context()。如果您直接将CSS添加到index.html,您仍然可以使用封装,您不需要禁用视图封装。Angular2不会重写此类样式,而是将其应用于页面中的所有元素(在支持原生阴影DOM的浏览器中使用
ViewEncapsulation.Native
时除外)
:host-context(.theme-1) .header {
    background-color: red;
}