2016-07-15 75 views
2

我从JSON中的beehance API加载了一些内容,其中包含一些文本和样式信息,使其看起来像它在编辑器中配置的样子。Angular2动态样式表元素

包含在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> 
    ` 
}) 

但插不工作,有没有办法做这样的事情?

回答

0

您可以直接添加动态风格的元素

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

,但目前还没有办法在风格本身使用绑定。

相关问题

+0

我不能使用ngStyle,除非我使用一些算法来搜索该字符串中的类,并添加指令,如果我这样做,它会工作,当我把结果字符串放入innerHTML指令?我认为我正在寻找的是类似于我看到的问题2567 –

+0

。我错过了innerHTML部分。 Can'r您只需将样式内联添加到您添加的HTML。否则,我不认为Angular2提供了任何东西。 –

2

我发现这个解决方案(这是主要的黑客攻击,但它的工作原理):

的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 /应用/ style1.css.ts

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

SRC /应用/ style2.css.ts

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

的src /应用程序/应用程序/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; 
    } 
    } 
}