[angularjs] AngularJS ng-style with a conditional expression

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?

This question is related to angularjs angularjs-directive

The answer is


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

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


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


You can achieve it like that:

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

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


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>

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>

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;
}

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>

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.


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