【问题标题】:Inject CSS variable names that come form the server (Angular 12)注入来自服务器的 CSS 变量名 (Angular 12)
【发布时间】:2021-08-25 12:37:44
【问题描述】:

我正在尝试找到将 css 变量注入 Angular 应用程序的最佳解决方案(目前使用 Angular 12)。

这是我正在使用的代码:

 private injectStyles(data: any) {
    const styles = this.document.createElement('STYLE') as HTMLStyleElement;
    styles.id = 'dynamic-css';

    this.test = `:root {      
      --main-bg-color: black;
    }`;
    
    styles.innerHTML = this.test;
    this.renderer.appendChild(this.document.head, styles);
}

这段代码在 app.component.ts 文件上执行,效果很好,我可以在整个应用程序中使用这个 css 变量。 我现在想要实现的是使用来自服务器的数据扩展 this.test 对象,并应用之前在我的视觉设置模块上设置的这些自定义 css 值。

Css 变量不能有 "" 引号。 "--button-color": "#a86c6c"(这是我从服务器得到的),我想在 this.test 对象上注入这个不带引号的属性,但我不能这样做。有什么想法吗?

非常感谢任何帮助, 谢谢。

【问题讨论】:

  • 使用String#replaceAll() 从服务器数据中删除引号对您有用吗?比如:let cleanedData = data.replaceAll('"', '');?
  • 我试过没有运气:(
  • @Rambo 请试试这个,var test = {"--button-color": "#a866c", "background-color": "red"}; var test1 = JSON.stringify(test); test1.replaceAll('"', '')

标签: css angular css-variables angular12


【解决方案1】:

Object.keys是你的朋友

 let dataString = '';
 Object.keys(data).forEach(key => {
    dataString += `${key}: ${data[key]};`
 });
 this.test = `:root {      
  --main-bg-color: black;
  ${dataString}
}`;

如果需要,您可能需要像这样为值添加引号

`dataString += `${key}: "${data[key]};"`

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    相关资源
    最近更新 更多