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

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

问题描述

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

app.component.ts

customCss : 任何;构造函数(){}ngOnInit(){this.customCss['color'] = "红色";}

app.component.html

<span class="custom_css">这是 angular 5 应用程序</span>

<风格>.custom_css{颜色:{{customCss.color}};}</风格>

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

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

感谢任何帮助.

解决方案

您可以使用 [ngStyle] 指令:

这是 angular 5 应用程序</span>

或者像这样:

这是 angular 5 应用程序</span>

在组件中:

applyStyles() {const 样式 = {'颜色':'红色'};返回样式;}

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

customCss : any;

constructor(){}

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

app.component.html

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

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

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

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

Any help is appreciated.

解决方案

You can use [ngStyle] directive:

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

Or like so:

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

And in component:

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

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

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