Shweta Singh
Shweta Singh

Reputation: 67

Angular2 - Two way binding for input Field

I have an input field of type number. When the user enter multiple zeros (0s) and moves to the next input field, the multiple zeros should go back to single 0.

I have tried the following code in the plunkr: https://plnkr.co/edit/dyCp5ZMKOkZvcsw4F8og?p=preview

<input [(ngModel)]="value" type="number" class="form-control" id="valueId" 
(ngModelChange)="valuechange($event)">

valuechange(newValue) {
//newValue = newValue.toString().replace(/^0+/, '0');
newValue=parseInt(newValue.toString());
console.log(newValue);
}             

Upvotes: 3

Views: 14981

Answers (1)

Pardeep Jain
Pardeep Jain

Reputation: 86720

You just need to set 0 as a string when the value is 0, and call function onchange instead. like this

<input [(ngModel)]="value" type="number" class="form-control" id="valueId" 
      (change)="valuechange($event)">


if(this.value === 0){
      this.value = '0';
}

PS: No need to convert using parseInt and toString()

Working Example

Upvotes: 6

Related Questions