Angular2动态样式表元素 [英] Angular2 dynamic stylesheet element

查看:66
本文介绍了Angular2动态样式表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过JSON中的beehance API加载一些内容,该内容具有一些文本和样式信息,以使其看起来像在编辑器中配置的一样.

I'm loading some content from the beehance API in JSON, which has some text and the style info to make it look as it was configured in the editor.

JSON中包含的文本具有html标记,我将其添加为[innerHTML]

the text contained in the JSON has html tags and I add it with [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>元素?
我尝试在模板中使用样式标签,但不知道如何在其中进行插值.

so is there an Angular2 way I can append some generated css to a <style> element?
I tried with a style tag inside the template but I don't know how to interpolate there.

样式元数据不起作用,因为样式是动态获取的,并且根据项目而有所不同.

The style metadata doesn't work because the styles are dynamically fetched and they vary depending on the project.

我想要的是这样的东西:

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

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

But the interpolation doesn't work, is there a way to do something like that?

推荐答案

我找到了这个解决方案(主要是hack,但是可以用):

I found this solution (it is mostly the hack, but it works):

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;
    }
  }
}

这篇关于Angular2动态样式表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆