296

I am handling my issue like this:

ng-style="{ width: getTheValue() }"

But to avoid having this function on the controller side, I would much prefer to do something like this:

ng-style="{ width: myObject.value == 'ok' ? '100%' : '0%' }"

How can I do this?

4
  • 19
    what version of angular are you using? At least with 1.1.5 this is possible without any changes. demo Commented Oct 15, 2013 at 7:56
  • I am using 1.0.8 :) Oh too bad, I should really try to upgrade then... thanks! Commented Oct 16, 2013 at 3:22
  • 4
    Although that with 1.1.5 your code is working, if you use other style properties instead of width (e.g. font-size) your code won't work until you change it to: ng-style="{ 'font-size': myObject.value == 'ok' ? '20px' : '10px' }" (must surround the style property with quotes). Commented Dec 15, 2017 at 10:02
  • I dont know this is helpful but for new comers you can use ng style with an object but like this ng-style="objectBit ? { 'border':'1px solid red'} : { 'border': 'none' }" Commented Mar 21, 2018 at 19:47

12 Answers 12

400

simple example:

<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>

{'background-color':'green'} RETURN true

OR the same result:

<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

other conditional possibility:

<div ng-style="count === 0 && {'background-color':'green'}  || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>
Sign up to request clarification or add additional context in comments.

5 Comments

How might I accomplish this but with multiple independent styles/conditions? Thanks, great answer btw.
@Arthur your example is going to check isTrue and {'background-color':'green'} OR it is going to check only isTrue and will put background how it will work please explain anyone?
@rajnish-rajput it is going to check isTrue and put background, {'background-color':'green'} by default return true as a style object
This does indeed work, but the syntax is really weird. Any links to documentation of this or any input on why it works with &&- and ||-operators?
@ArthurTsidkilov what if I want to restrict ng-style to run only once? I can't use ng-class and controller scope variable, I need to calculate all containers heights at runtime but once a property is set I want to restrict it to avoid continues execution.
127

As @Yoshi said, from angular 1.1.5 you can use-it without any change.

If you use angular < 1.1.5, you can use ng-class.

.largeWidth {
    width: 100%;
}

.smallWidth {
    width: 0%;
}

// [...]

ng-class="{largeWidth: myVar == 'ok', smallWidth: myVar != 'ok'}"

7 Comments

Okay, thanks! I just wondered if there was a way to do it without using any classes, but everything directly using Angular on the template.
And if I'm using angular >1.1.5 ?
This doesn't exactly answer the question.
This question literally asks for an example with ng-style and the accepted answer with 100+ votes does not provide that.
this is the wrong answer, the answer from @Arthur below is correct.
|
123

You can achieve it like that:

ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

1 Comment

This should be the accepted answer. It actually uses ng-style and allows for conditionals for each style.
46

@jfredsilva obviously has the simplest answer for the question:

ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

However, you might really want to consider my answer for something more complex.

Ternary-like example:

<p ng-style="{width: {true:'100%',false:'0%'}[myObject.value == 'ok']}"></p>

Something more complex:

<p ng-style="{
   color:       {blueish: 'blue', greenish: 'green'}[ color ], 
  'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]
}">Test</p>

If $scope.color == 'blueish', the color will be 'blue'.

If $scope.zoom == 2, the font-size will be 26px.

angular.module('app',[]);
function MyCtrl($scope) {
  $scope.color = 'blueish';
  $scope.zoom = 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl" ng-style="{
   color:       {blueish: 'blue', greenish: 'green'}[ color ], 
  'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]
}">
  color = {{color}}<br>
  zoom = {{zoom}}
</div>

2 Comments

interesting syntax {<value>:'<string>'}[<$scope.var>]}, where it come from?
It's just using bracket notation to access the object. color['blueish'] == 'blue'
11

if you want use with expression, the rigth way is :

<span class="ng-style: yourCondition && {color:'red'};">Sample Text</span>

but the best way is using ng-class

1 Comment

Syntax Error: Token '%3A' is%20an%20unexpected%20token at column 9 of the expression [ng-style%3A%...
10

On a generic note, you can use a combination of ng-if and ng-style incorporate conditional changes with change in background image.

<span ng-if="selectedItem==item.id"
              ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)','background-size':'52px 57px','padding-top':'70px','background-repeat':'no-repeat','background-position': 'center'}"></span>
        <span ng-if="selectedItem!=item.id"
              ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)','background-size':'52px 57px','padding-top':'70px','background-repeat':'no-repeat','background-position': 'center'}"></span>

1 Comment

This caused Uncaught Error: Template parse errors: Can't bind to 'ng-style' since it isn't a known property of 'div' error for me
7

For single css property

ng-style="1==1 && {'color':'red'}"

For multiple css properties below can be referred

ng-style="1==1 && {'color':'red','font-style': 'italic'}"

Replace 1==1 with your condition expression

Comments

5

also this syntax for ternary operator will work:

  ng-style="<$scope.var><condition> ? {
        '<css-prop-1>':((<value>) / (<value2>)*100)+'%',
        '<css-prop-2>':'<string>'
      } : {
        '<css-prop-1>':'<string>',
        '<css-prop-2>':'<string>'
      }"

where <value> are $scope property values. In example:

ng-style="column.histograms.value=>0 ? 
  {
    'width':((column.histograms.value) / (column.histograms.limit)*100)+'%',
    'background':'#F03040'
  } : {
    'width':'1px',
    'background':'#2E92FA'
  }"

```

this allows for some calculaton into the css property values.

Comments

5

I am doing like below for multiple and independent conditions and it works like charm:

<div ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''} && valueFromNG-Repeat === '{{dayOfToday}}' ? {'font-weight': 'bold'} : {'font-weight': 'normal'}"></div>

Comments

3

EDIT:

Ok i was previously not aware that AngularJS usually refers to Angular v1 version and only Angular to Angular v2+

This answer only applies for Angular

Leaving this here for future reference..


Not sure how it works for you guys but on Angular 9 i have to wrap ngStyle in brackets like this:

[ng-style]="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

Otherwise it doesn't work

Comments

2

I am using ng-class for adding style :-

 ng-class="column.label=='Description'  ? 'tableStyle':                     
           column.label == 'Markdown Type' ? 'Mtype' : 
           column.label == 'Coupon Number' ? 'couponNur' :  ''
           "

Using ternary operator along with ng-class directives in angular.js for giving style. Then define the style for class in .css or .scss file. Eg :-

.Mtype{
       width: 90px !important;
       min-width: 90px !important;
       max-width: 90px !important;
      }
.tableStyle{
         width: 129px !important;
         min-width: 129px !important;
         max-width: 129px !important;
}
.couponNur{
         width: 250px !important;
         min-width: 250px !important;
         max-width: 250px !important;
}

Comments

0

Simplest is to use

[style.width]="getTheValue()"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.