Sampath
Sampath

Reputation: 65948

Apply CSS class dynamically on TS file

I have inline HTML content on ts file as shown below.

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

Now I need to apply color: red according to the condition.

i.e if(this.isSpentOver) color:red else default

I can do this in HTML file like below:

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

But how can I do that on ts file?

Upvotes: 2

Views: 14526

Answers (1)

Z. Bagley
Z. Bagley

Reputation: 9270

Update:

.ts

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

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

Old

If the HTML is generated in your component.ts you can simply add that to the styling there, but it won't dynamically change.

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

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

If you're looking to dynamically style generated html, one of the easier routes is to just use an ElementRef and any time your spentData changes (and the color needs to be updated) call the method that gets the elementRef and changes the color. There are a lot of solid SO questions/answers on Angular, ElementRef, and querySelector() methods so I won't drop how that works here.

Upvotes: 1

Related Questions