在TS文件上动态应用CSS类
问题描述:
我在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
文件?
答
更新:
.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的问题/答案,所以我不会放弃这里的工作方式。
非常感谢您的指导。有用 :) – Sampath