从Angular 5控制CSS变量 [英] Control CSS variable from Angular 5
问题描述
是否有任何方法可以使用Angular方法控制在组件的根级别定义的CSS变量?在JavaScript中,在根目录级别设置时为document.documentElement.style.setProperty()
.
Is there any way to control a CSS variable defined at a component's root level using Angular methods? In JavaScript, we have document.documentElement.style.setProperty()
when we set at root level.
在角度上,我们可以使用':host'声明css变量以在组件内进行全局访问吗?还是我们需要使用类似':: ng-deep:root'的东西?
In angular, can we use ':host' to declare css variable for global access within component? or do we need to use something like '::ng-deep :root'?
以下问题也未得到解答: 角度:使用Renderer 2添加CSS变量
The following question also remains unanswered: Angular: Use Renderer 2 to Add CSS Variable
推荐答案
是的,您可以在根范围内设置变量:
Yes you can set variables in root scope:
:root {
--main-color: red
}
是的,您可以使用:host
选择器来定位承载该组件的元素.
Yes you can use :host
selector to target element in which the component is hosted.
:host {
display: block;
border: 1px solid black;
}
您还可以使用:host-context
定位组件的任何祖先. :host-context()选择器在组件宿主元素的任何祖先(直到文档根)中寻找CSS类.
You can also use, :host-context
to target any ancestor of the component. The :host-context() selector looks for a CSS class in any ancestor of the component host element, up to the document root.
:host-context(.theme-light) h2 {
background-color: #eef;
}
注意:已弃用::ng-deep
或/deep/
或>>>
.
在此处了解更多信息:特殊的Angular CSS选择器
Read more about it here: special css selectors in angular
仅提供其他信息. 它既可以在':root'内部也可以在':host'内部工作 我们可以通过以下方式为它们设置值:
Just an additional information. It works both inside ':root' as well as ':host' We can set values to them by:
constructor(private elementRef: ElementRef) { }
然后
this.elementRef.nativeElement.style.setProperty('--color', 'red');
这篇关于从Angular 5控制CSS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!