127

I have a div that I want to style based on a condition.

If styleOne is true I want a background colour of red. If StyleTwo is true, I want the background colour to be blue. I've got half of it working with the below code.

    <div id="myDiv" [ngStyle]="styleOne && {'background-color': 'red'}">

Is it possible to add a condition to say:

  • if styleOne is true, do this
  • if styleTwo is true, do this?

Edit

I think i've resolved it. It works. Not sure if it's the best way:

<div id="div" [ngStyle]="styleOne && {'background-color': 'red'} || styleTwo && {'background-color': 'blue'}">
Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
MegaTron
  • 3,133
  • 6
  • 28
  • 45

5 Answers5

258

For a single style attribute, you can use the following syntax:

<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">

I assumed that the background color should not be set if neither style1 nor style2 is true.


Since the question title mentions ngStyle, here is the equivalent syntax with that directive:

<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">
Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
59

You can use an inline if inside your ngStyle:

[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"

A better way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:

[style.background-color]="myColorVaraible"
Isaac Gregson
  • 1,999
  • 1
  • 21
  • 31
Gili Yaniv
  • 3,073
  • 2
  • 19
  • 34
39
[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"
Apurv Chaudhary
  • 1,672
  • 3
  • 30
  • 55
5
<ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>
Fahimeh Ahmadi
  • 813
  • 8
  • 13
2
[ngStyle]="{ 'top': yourVar === true ? widthColumHalf + 'px': '302px' }"
StupidWolf
  • 45,075
  • 17
  • 40
  • 72
Ajay Kumar
  • 41
  • 2