4

I want to compare angular 2 expressions. I got array of data in numeric string from my database i need to convert this to number before give a condition with ngClass for styling. how can i convert this type. any idea?

  <td [ngClass]= "{'positive': gbh.Last > 0, 'negative': gbh.Last < 0}"> {{gbh.Last}} </td>
U rock
  • 677
  • 2
  • 11
  • 27

2 Answers2

8

This answer is the typescript way: so answer

Number('1234') // 1234
Number('9BX9') // NaN

The other answer looks like it would be for int not numbers. You are better off using the plus symbol.

var x = "32";
var y = +x; // y: number

Ref answer:

trees_are_great
  • 3,583
  • 3
  • 25
  • 54
  • 2
    Yes those are all valid ways to convert to number in JS and TypeScript, however the question asked about converting to number _within expressions in Angular template HTML_. Your answer makes no mention of this. It's worth noting that expression syntax for Angular templates is very limited, and symbols such as `Number` and `var` are not allowed. – jcairney Apr 03 '20 at 19:38
  • 1
    @jcairney `Number` and `var` obviously will not work inside template. but that `+` works in template.. – Bal Krishna Jha Oct 16 '20 at 13:48
5

As far as I know, you can not convert your numeric string to number inside the Angular expression.

The best practice will be to define a method in your controller which will solve your expression by using 'parseInt'

  function isPositive (x: String, y: number): boolean {
      return (parseInt(x, 10) < y);
  }
Antoine Guittet
  • 456
  • 1
  • 3
  • 14