0

I want to give conditional class a div. But my problem is, I want "myClassCondition" as a string like below. When I write like this <div [class]="7 > 6 ? 'bg-red' : null"> MyText </div>, it is working perfectly. But I want send from .ts file as variable like below. How can I do this?

<div [class]="myClassCondition"> MyText </div>

-

myClassCondition = "7 > 6 ? 'bg-red' : null";
realist
  • 2,155
  • 12
  • 38
  • 77

2 Answers2

2

You can try the following

.component.html

<div [class.bg-red]="myClassCondition"> MyText </div>

.component.ts

myClassCondition = 7 > 6 ? true : false;
Sarthak Aggarwal
  • 2,284
  • 1
  • 8
  • 12
  • Thanks for your reply @SarthakAggarwal. This worked. But what I was looking for is selemmn's answer. But this information also very helpful for me. Because i don't know usage like `[class.bg-red]`. I learnt new thing. – realist Oct 26 '18 at 07:51
1

Just remove the quotes in your Ts part to

myClassCondition = 7 > 6 ? 'bg-red' : null;

Stackblitz

SeleM
  • 9,310
  • 5
  • 32
  • 51