Angular – Style Based On Condition

Issue

I am trying to change the style of a background to green if a value is equal or greater than 16 and if a string contains the following word ‘hdl’.

I done it with two separate conditions but it messed up my results and I don’t think its the best way to do it.

So to reiterate, I’m trying to say if value.runners.length => 16 and value.marketName contains the string ‘hdl’ anywhere within it change background to #00FFBE if not don’t add this background.

<a ng-repeat="(key, value) in events" class="list-group-item" ng-if="value.runners.length => '16' && value.marketName.includes(hdl)" ng-style="{ background:'#00FFBE' }" ng-click="showRunners(value.marketStartTime,value.marketName,value.runners,value.marketStartTime)" >
                    {{value.marketStartTime | date:'dd-MMMM-yyyy h:mma'}} - {{value.marketName}}
                    <any style="float: right;"> 
                        <i class="fa fa-user"></i> {{value.runners.length}}

                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <i class="fa fa-chevron-right"></i>
                    </any>
                </a>


                <a ng-repeat="(key, value) in events" class="list-group-item" ng-if="value.runners.length  <= '15'" ng-click="showRunners(value.marketStartTime,value.marketName,value.runners,value.marketStartTime)" >
                    {{value.marketStartTime | date:'dd-MMMM-yyyy h:mma'}} - {{value.marketName}}
                    <any style="float: right;"> 
                        <i class="fa fa-user"></i> {{value.runners.length}}

                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <i class="fa fa-chevron-right"></i>
                    </any>
                </a>

Solution

There are a couple of ways you can do it.

Using ng-style

<span ng-style="{background-color:(CONDITIONS FOR GREEN)?'green':'red'">Text</span>

CONDITIONS can be either inline or your can call a function and return true/false

Using ng-class

<span ng-class="{'my-green-css':CONDITIONS FOR GREEN,'my-red-css':CONDITIONS FOR RED}"> Text </span>

Where you have a CSS class for my-green-css and my-red-css.
The CONDITIONS can either be inline, or you can call a function and return true/false.

Answered By – Scott

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published