在角度模板的样式标签中使用变量? [英] Use variable in style tag in angular template?

查看:56
本文介绍了在角度模板的样式标签中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发angular 5应用程序,并且我要求在模板的样式标签中应用动态css. 我已经尝试了一些解决方案,但是它们不起作用.

I am working on angular 5 application, and I have requirement of applying dynamic css in style tag in template. I have tried some solutions but they are not working.

app.component.ts

app.component.ts

customCss : any;

constructor(){}

ngOnInit(){
   this.customCss['color'] = "red";
}

app.component.html

app.component.html

<div>
   <span class="custom_css">This is angular 5 application</span>
</div>

<style>
   .custom_css{
      color: {{customCss.color}};
   }
</style>

当我在浏览器中检查custom_css类时,它会以样式显示

When I inspect the custom_css class in browser then in style it shows

.custom_css{
   color: {{customCss.color}};
}

感谢您的帮助.

推荐答案

您可以使用[ngStyle]指令:

<span [ngStyle]="{'color': 'red'}">
 This is angular 5 application
</span>

或者像这样:

<span [ngStyle]="applyStyles()">
 This is angular 5 application
</span>

在组件中:

applyStyles() {
    const styles = {'color' : 'red'};
    return styles;
}

这篇关于在角度模板的样式标签中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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