【问题标题】:Angular2 dynamic stylesheet elementAngular2动态样式表元素
【发布时间】:2016-11-19 03:52:27
【问题描述】:

我正在以 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 附加到 &lt;style&gt; 元素?
我尝试在模板中使用样式标签,但我不知道如何在那里插入。

样式元数据不起作用,因为样式是动态获取的,并且它们因项目而异。

我想要的是这样的:

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

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

【问题讨论】:

    标签: javascript css angular angular2-template


    【解决方案1】:

    我找到了这个解决方案(它主要是 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;
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      你可以直接给元素添加动态样式

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

      但目前无法在样式本身中使用绑定。

      相关问题

      【讨论】:

      • 我不能使用 ngStyle 除非我做一些算法来搜索该字符串中的类并添加指令,如果我这样做,当我将结果字符串放入 innerHTML 指令时它会起作用吗?我认为我正在寻找的是类似问题 2567
      • 我明白了。我错过了 innerHTML 部分。您能否将样式内联添加到您添加的 HTML 中。否则我不认为 Angular2 提供任何东西。
      猜你喜欢
      • 2017-07-10
      • 2017-02-09
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      相关资源
      最近更新 更多