1

I have a input type number in AngularJS as follows...

<input type="number"></input>

I want to achieve the following:

  • If user enters a positive value, it should display the same font and color

  • If the user displays a negative value, it should display font color in red indicating it is a negative number

Can someone please let me know how to achieve this dynamically?

3 Answers 3

1

You could do this.

HTML

<input type="number" ng-class="{negative: amount < 0, positive: amount > 0}" ng-model="amount"/>

CSS

.negative {
   color: red;
}
.positive {
    color: green;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi John, this works well. Wat if i have 2 classes. one class for positive value and one for negative value. How can i achieve that situation ?
Patrick, I have edited my answer to account for positive values as well. All you need to do is add a new condition to ng-class and also create an additional class to reflect that in the CSS.
1
<input type="number" ng-change="amountChanged()" ng-style="myStyle.color" ng-model="amount"/>

$scope.myStyle= {};
$scope.amountChanged = function () {

   if($scope.amount < 0)
   {
      $scope.myStyle.color= {"color":"green"};
   }
   else
   {
      $scope.myStyle.color= {"color":"blue"};
   }

}

Hope it helps.

1 Comment

instead of ng-style, can i use ng-class and assign a class directly ?
1
  <input type="number" ng-model="number">
    <label ng-show="number > 0" style="color:green;">You are Correct</label>
    <label ng-show="number < 0" style="color:red;">Your number is negative</label>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.