我在 ts
文件中有内联 HTML 内容,如下所示。
"<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 问题/答案,所以我不会在这里放弃它的工作原理。
关于css - 在 TS 文件上动态应用 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849230/