Reputation: 123
this is my html template code:
<input type="text" maxlength="5"
[(ngModel)]="groupInfo.discount" (keyup)="validateFloat($event)">
there is my validateFloat method:
validateFloat(event){
event.target.value = event.target.value.replace(/[^\d.]/g, "");
console.log(this.groupInfo.discount);
}
then when input value:
12adc
input element output value:
12
but the groupInfo.discount value is:
12a
i can't understand why the groupInfo.discount value is 12a
?
And how can i make the groupInfo.discount value is equal to input element's value?
my package dependencies:
"@angular/common": "2.0.0-rc.6",
"@angular/compiler": "2.0.0-rc.6",
"@angular/core": "2.0.0-rc.6",
"@angular/forms": "2.0.0-rc.6",
"@angular/http": "2.0.0-rc.6",
"@angular/platform-browser": "2.0.0-rc.6",
"@angular/platform-browser-dynamic": "2.0.0-rc.6",
"@angular/router": "3.0.0-rc.2",
Upvotes: 0
Views: 209
Reputation: 14564
It looks like your update isn't being picked up by ngModel properly.
Try doing your update asynchronously like this:
validateFloat(event){
setTimeout(() => {
event.target.value = event.target.value.replace(/[^\d.]/g, "");
console.log(this.groupInfo.discount);
}, 50);
}
ngModel has some unintuitive behaviour when you try to get fancy with it because of what it's trying to do - (reflect changes in your component to the DOM and changes to the DOM in your component). Because Angular doesn't allow you to change a value after it's checked during a change detection cycle, ngModel has to work asynchronously, which can lead to unexpected behaviour.
Upvotes: 0
Reputation: 3618
if you are using input && ngModel in template better than (keyup)
use (ngModelChange)
event
template.html
<input type="text" maxlength="5"
[(ngModel)]="groupInfo.discount" (ngModelChange)="validateFloat($event)">
I thinks its only the trigger issue
with event
Upvotes: 1