css - 在 TS 文件上动态应用 CSS 类

标签 css angular typescript sass ionic3

我在 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/

相关文章:

javascript - 如何在Wordpress主页中实现一个js动画

Angular Material 表 : Sorting not working

angular - 在 RxJs 6( ionic /Angular )中使用 map 和过滤器在对象数组中无法正常工作,过滤器被忽略

javascript - Angular typescript 将日期分配给 DateConstructor

javascript - 单击子组件 React Typescript 不起作用

node.js - 避免类型 '{}' 不可分配给类型 'X'

html - 为什么宽度是: 100% not working for my responsive design?

javascript - 使用类样式化 React 组件

jquery - 日期选择器焦点功能

ios - vips/vips8 文件在 IOS 的 Ionic cordova 中找不到 #include <vips/vips8>