如何在Angular2组件中操作scss变量 [英] How to manipulate scss variables in Angular2 components
问题描述
有没有一种方法可以更改在Angular2组件中声明的scss变量?我想根据用户选择动态添加主题,因此需要修改scss变量.我读到有关将所有scss变量保留在单独的scss文件中并将其导入其他scss文件中的信息.但是我可以将其导入到我的组件文件中并修改变量.这可行吗?TIA
Is there a way I can change scss variables declared in Angular2 component? I want to add the theme dynamically based on user selection and hence need to modify the scss variables. I read about keeping all scss variables in a separate scss file and importing the same in other scss file. But can i import the same in my component file and modify the variables. Is this feasible? TIA
目前,我正在使用mixin.代码在这里:
Currently I am using mixin. Code goes here:
// Color themes
$themes: (
default: #ff0000,
banana: #f1c40f,
cherry: #c0392b,
blueberry: #8e44ad,
leaf: #27ae60,
nightsky: #2980b9
);
// Helper theme mixin
@mixin theme($name, $color) {
.#{$name}{
background-color: lighten($color, 30%);
}
.#{$name} {
h1{
color: $color;
}
}
.#{$name} {
nav{
a{
color: $color;
}
}
}
}
但是有什么办法可以从Angular组件更改$ themes映射中的变量.
But is there a way I can alter the variables inside $themes map from Angular component.
推荐答案
根据Sass的性质,这不可能:它是一个构建工具,是一个预处理器.Angular仅了解CSS(尽管 Component
元数据中的 styles
和 styleUrls
属性).
This is impossible by nature of Sass: it's a build-time tool, a pre-processor. Angular only knows about CSS (though the styles
and styleUrls
property in Component
metadata).
这意味着,当Angular开始使用您的样式时,Sass已经被编译为CSS.您无法在运行时更改Sass变量,因为此时它们不存在.
This means that by the time Angular has got its hands on your styles, Sass has already been compiled to CSS. You cannot change Sass variables in run-time because they do not exist anymore at that point.
您可以改为使用自定义属性和通过常规JavaScript进行更改.
You can instead use custom properties and change them via regular JavaScript.
这篇关于如何在Angular2组件中操作scss变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!