Reputation:
I am working on an angular application. I have a css class in div
which has general properties like font
, padding
, background-color
etc. html code is something like this.
<div class="myCss">
//my code
</div>
in CSS file, have css like this
div.myCss {
color: white;
font-size: 23px;
background-color: yellow;
}
For a certain condition, I need to change background-color
. If myFlag
is true, I want background-color
to be black, otherwise yellow. I tried using ngClass
, but in that when myFlag == true
I need to write the whole css just to change background-color
. Is there is any way, I can only change background-color
on the basis of flag instead of making a new css class with exact same properties as previous one's just with background color change.
I have table in html as follows:
1 2 3 4 5and in css class I have following css:
table th {
border-collapse: collapse;
color: white;
background-color: #002BA4;
padding: 3px 4px 3px 4px;
}
For the same flag, I want to change background-color
of this th
too. How I can do this?
Upvotes: 0
Views: 6548
Reputation: 8301
<div class="myCss" [style.background-color]="getBackgroundColor()">
//my code
</div>
<th [style.background-color]="getBackgroundColor()">1</th>
Please use the style attribute on div using your myFlag attribute
TS Code: getBackgroundColor() { return this.myFlag ? 'black': 'yellow'; }
Upvotes: 0
Reputation: 4267
There're two ways you could approach this:
Option 1
Create a variable to store the style, for example, this will allow you to be able to use this variable multiple times in your template.
let color = myFlag? 'black' : 'yellow';
then in your template, you can do this:
<div [className]="color"></div>
However, this only set the class name so you still need to style those classes.
.black{
background-color: black;
}
.yellow{
background-color: yellow;
}
Option 2
You could use style binding like this:
<div [style.backgroundColor]="!myFlag ? 'yellow': 'black'" ></div>
this option will require you to write the same thing in the case where you'll be wishing to change the background-color
.
Upvotes: 2