在我的 angular 元素中,我在顶级 中定义了一些 css 变量。样式.scss 这样的文件。我在很多地方使用这些变量来保持整个主题的一致性。
:root {
--theme-color-1: #f7f7f7;
--theme-color-2: #ec4d3b;
--theme-color-3: #ffc107;
--theme-color-4: #686250;
--font-weight: 300
}
如何从 动态更新这些变量的值app.component.ts ?什么是清洁方式以 Angular 来做到这一点?
最佳答案
您可以使用更新它们
document.documentElement.style.setProperty('--theme-color-1', '#fff');
如果你想更新很多值,那么创建一个对象 this.styles = [
{ name: 'primary-dark-5', value: "#111" },
{ name: 'primary-dark-7_5', value: "#fff" },
];
this.styles.forEach(data => {
document.documentElement.style.setProperty(`--${data.name}`, data.value);
});
这里主要的是document.documentElement.style.setProperty
.此行允许您访问根元素(HTML 标记)并分配/覆盖样式值。请注意,变量的名称应在两个位置(css 和 js 文件)匹配
如果你不想使用文档 API,那么你可以直接在 HTML 标签上使用内联样式
const styleObject = {};
this.styles.forEach(data => {
styleObject[`--${data.name}`] = data.value;
});
然后在您的模板文件中使用 ngStyle (https://angular.io/api/common/NgStyle)Set a collection of style values using an expression that returns key-value pairs.
<some-element [ngStyle]="objExp">...</some-element>
<html [ngStyle]="styleObject" >...</html> //not sure about quotes syntax
上述方法做同样的事情,“更新根元素值”,但以不同的方式。
当您使用
:root
, 样式自动附加到 HTML 标签
关于css - 以 Angular 动态更改css变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63101535/