javascript - Angular2 动态样式表元素

标签 javascript css angular angular2-template

我正在从 JSON 格式的 beehance API 加载一些内容,其中包含一些文本和样式信息,使其看起来与编辑器中配置的一样。

JSON 中包含的文本具有 html 标签,我使用 [innerHTML] 添加它

{
  text: '<div class="sub-title">Lorem ipsum</div>  <div class="paragraph">dolor sit amet</div>',
  ...
}

样式类似于

"paragraph": {
  "color": "#3B3B3B",
  "font_family": "arial,helvetica,sans-serif",
  "font_size": "12px",
  "line_height": "1.4em",
  "text_align": "left"
},
"subtitle": {
  "color": "#000000",
  "font_family": "arial,helvetica,sans-serif",
  "font_size": "14px",
  "line_height": "1.6em",
  "text_align": "right"
}

有没有一种 Angular2 方法可以将一些生成的 css 附加到 <style>元素?
我尝试在模板内使用样式标签,但我不知道如何在其中插入。

样式元数据不起作用,因为样式是动态获取的,并且样式随元素而变化。

我想要的是这样的:

@Component({
  template: `
    <style>
    .paragraph {
      {{styles.paragraph}}
    }
    </style>
    `
})

但是插值不起作用,有没有办法做类似的事情?

最佳答案

我找到了这个解决方案(主要是 hack,但它有效):

src/index.html

<!doctype html>
<html>
  <head>
    <base href="/">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.png">
  </head>
  <body>
    <style id="theme_styles"></style>
    <app-root></app-root>
  </body>
</html>

src/app/style1.css.ts

export const style1 = `
  body {
    background: red;
  }
`;

src/app/style2.css.ts

export const style2 = `
  body {
    background: blue;
  }
`;

src/app/app/component.ts

import { Component } from '@angular/core';
import { style1 } from './style1.css';
import { style2 } from './style2.css';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  private themeElement: Element = document.getElementById('theme_styles');
  private isStyle1: boolean = false;

  constructor() {
    this.themeElement.innerHTML = style1;
  }

  ngOnInit() {
    if (this.isStyle1) {
      this.themeElement.innerHTML = style1;
    } else {
      this.themeElement.innerHTML = style2;
    }
  }
}

关于javascript - Angular2 动态样式表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404537/

相关文章:

angular - 使用从其自己的组件上的可观察对象检索的数据的方法在用作 Input() 时返回未定义

javascript - 从 JavaScript 使用时如何确保释放 wasm 内存

javascript - 使用 Map() 函数通过 ReactJS 提取双层嵌套的 JSON 数据

css - asset_path 在生产环境返回错误的路径

php - 如果我的 javascript 函数返回 false,如何停止在下一个选项卡上滚动或移动

angular - 单元测试 Angular/Redux 中是否已清除所有订阅

javascript - 在 Node 中将 UUID 转换为二进制文件

javascript - Javascript 中的链表和对象错误

html - SVG 在左侧 div 可调整大小,div 在右侧 CSS 的右上角

visual-studio - 什么是 Visual Studio TypeScript 虚拟项目?如果我在外部编译,我怎样才能摆脱它呢?