有什么方法可以使用角度方法来控制在组件根目录级别定义的css变量。在javascript中,当我们在根级别进行设置时,我们具有document.documentElement.style.setProperty()。
在角度上,我们可以使用':host'声明css变量以在组件内进行全局访问吗?还是我们需要使用类似':: ng-deep:root'的东西?
以下问题也未得到解答: 角度:使用Renderer 2添加CSS变量
是的,您可以在根范围内设置变量:
:root {
--main-color: red
}
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用:host选择器来定位承载组件的元素。
:host {
display: block;
border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用:host-context来定位组件的任何祖先。:host-context()选择器在组件宿主元素的任何祖先(直至文档根)中查找CSS类。
:host-context(.theme-light) h2 {
background-color: #eef;
}
Run Code Online (Sandbox Code Playgroud)
注意:::ng-deep或/deep/或>>>已被弃用。
在这里阅读更多有关它的信息:角度的特殊css选择器
只是附加信息。它在':root'和':host'内部都可以使用。我们可以通过以下方式为它们设置值:
constructor(private elementRef: ElementRef) { }
然后
this.elementRef.nativeElement.style.setProperty('--color', 'red');
在组件中使用 css 变量(使用 viewEncapsulation)的最具建设性和模块化的方式如下:
// global css
:root {
--main-color: red
--alt-color: blue
}
// inside component component css
::ng-deep :root {
--specific-css-var: var(--main-color)
}
:host {
background-color: var(--specific-css-var)
}
:host(.conditional-class) {
--specific-css-var: var(--alt-color)
}
Run Code Online (Sandbox Code Playgroud)
注意:尽管::ng-deep已被弃用,但它尚未被替换(并且没有替换),可以在这样的几个讨论中阅读