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";
4
  • You can check out this link Commented Oct 26, 2018 at 7:38
  • Thanks but there isn't what I was looking for in that link @SarthakAggarwal Commented Oct 26, 2018 at 7:41
  • you want to send class name from .ts ? Commented Oct 26, 2018 at 7:44
  • No I want send condition not class name @SarthakAggarwal Commented Oct 26, 2018 at 7:45

2 Answers 2

2

You can try the following

.component.html

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

.component.ts

myClassCondition = 7 > 6 ? true : false;
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

Just remove the quotes in your Ts part to

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

Stackblitz

5 Comments

@HasanOzdemir it works for me , unless there is an issue with your class itself (bg-red). check the updated answer i provided a stackblitz;
Thanks a lot @selemmn. But my IDE underline the code in .ts file like an error.
Visual studio 2017
Opened and closed My IDE. and it's fixed. Thanks again @selemmn
@HasanOzdemir Welcome :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.