Billy Assim
Billy Assim

Reputation: 227

Angular data binding returning NaN when value is zero

I'm doing some simple data binding like so:

<input type="text" class="form-control" model="amount">
<label>Your amount is {{amount * 10 }}</label>

However, initially, when the text input is empty it returns NaN.

How can I prevent this from happening with Angular?

Upvotes: 2

Views: 31875

Answers (5)

Niranjana V S
Niranjana V S

Reputation: 177

a = (a*10)+b;

where b is undefined value.so, we are getting NaN value.

a = (a*10) || b;

this || operator instead of "+" solved my issue

Upvotes: 0

Sridharkarthik
Sridharkarthik

Reputation: 11

Your amount is

{{ (amount * 10) || "0" }}

This works fine.

Upvotes: 1

Pradnya Bhagat
Pradnya Bhagat

Reputation: 219

Your amount is {{ (amount * 10) || "0" }}

Upvotes: 0

Sander Elias
Sander Elias

Reputation: 754

You can try this:

<input type="text" class="form-control" model="amount">
<label>Your amount is {{ (+amount) * 10 }}</label>

HTML text inputs are text by definition. the added + will convert it to an number prior to being used.

Upvotes: 8

Subash Selvaraj
Subash Selvaraj

Reputation: 3385

Use ternary operator to check isNaN in your tempalte like below.

<input type="text" class="form-control" model="amount">
<label>Your amount is {{ (!isNaN(amount)) ?  (amount * 10) : '' }}</label>

Upvotes: 1

Related Questions