2017-10-20 44 views
1

我在ts文件中有嵌入式HTML内容,如下所示。在TS文件上动态应用CSS类

"<div style=\"font-size: 20px;\">" + remainingAmount.toLocaleString() + "</div>" 

现在我需要根据条件应用color: red

if(this.isSpentOver) color:red else default

我能做到这一点HTML文件象下面这样:

[ngClass]="{'color-red': isSpentOver}" 

但我怎么能做到这一点的ts文件?

回答

1

更新:

.TS

myMethod(){ 
    if (spent > totalBudget) { 
      this.color = "red"; 
     } 
    } 

showChart(){ 
     "<div style=\"font-size: 20px;color:" + this.color + "\">" + 
         remainingAmount.toLocaleString() + "</div>" 
    } 

如果HTML中产生的component.ts你可以简单地添加到造型存在,但它将不会动态改变。

myInnerHtml = "<div style=\"font-size: 20px;color: " + this.isSpentOver() + "\">" + remainingAmount.toLocaleString() + "</div>" 

isSpentOver(): string { 
    (this.spentData)? return 'red': return 'initial'; 
} 

如果你正在寻找动态的风格生成html,更容易的途径之一是只使用一个ElementRef和(需要更新和颜色)的spentData变化随时调用获取方法elementRef并更改颜色。 Angular,ElementRef和querySelector()方法中有很多关于SO的问题/答案,所以我不会放弃这里的工作方式。

+0

非常感谢您的指导。有用 :) – Sampath