绑定值到 <Style> 标签 Angular 2 模板

Binding value to <Style> tag Angular 2 template

我有一个组件使用 html 文件中的模板,模板像这样

<div class="abc"></div>
<style>
    .abc {
        background-color: {{myColor}}
    }
</style>

有没有办法动态绑定 background-color 的值? 实际上我可以通过将 css 移动到内联 html 来做到这一点 <div class="abc" [style.background-color]="myColor"></div> ,但由于某些原因我不能这样做。

有人有什么想法吗?非常感谢!

您可以使用 ng2 styler 或编写自己的装饰器,根据 ng2 样式器代码

插入作为文本导入的 css

您可以使用四个装饰器函数:

metaInformation = window['Reflect'].getOwnMetadata('annotations', target)

然后:

for (let metadata of metainformation){ 
   if (metadata instanceof ComponentMetadata){
     //interpolate somecsstext and add it to to metadata.styles
     //as if it was added from the styles property 
     //of the component decorator metadata
     metadata.styles = [...metadata.styles, somecsstext
        .replace(/{{([a-z1-9]+)}}/ig, function (match, prop) {
          return yourVaribles[prop];
        })];


   }
}