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>
3
  • stackoverflow.com/questions/21398319/… Commented Mar 28, 2017 at 12:05
  • 1
    I'm not at my computer right now ... but does this work? +gbh.Last > 0 Commented Mar 28, 2017 at 17:11
  • if array returns number it works exactly as i shown above. Commented Mar 29, 2017 at 7:41

2 Answers 2

9

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:

Sign up to request clarification or add additional context in comments.

2 Comments

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 Number and var obviously will not work inside template. but that + works in template..
6

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

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.