Issue
I have an currency input field that has to display data in a 2-way binding context. In other words, data from the model must be able to update the value, and data from the user must also be able to update the value.
My first attempt was something like this:
<input type="text" [(ngModel)]="price | currency">
This works fine in a one-way context. But whenever the user tries to edit the input, we get an error, EX:
"InvalidPipeArgument: '$123.00 is not a number' for pipe 'CurrencyPipe'"
This error makes sense, as the pipe is trying to apply the filter on the input value again, but the value this time around is our currency string, not a number.
I thought about trying to do something like this:
<input type="text" [ngModel]="price" (ngModelChange)="price = $event.target.value">
But the value here is going to be the same currency string as before. I guess I need to do something like undo_currency_filter($event.target.value)
, but I don't see any way to do this without writing a custom, and probably error prone method.
What would be the best way to accomplish this task in Angular, preferably without having to write a custom method such as described above?
Solution
I've figured out how to solve this in a somewhat elegant manner.
There's really no way around undoing the currency pipe, and there's nothing built in that does this. However, undoing it isn't as difficult as I would have thought. All you really have to do to covert the currency string back to a number is to remove the extra characters added by the filter. This can be done with a RegEx like this:
Number(currency.replace(/[^0-9.-]+/g,""))
So my template is now:
<input [ngModel]="price | currency" (change)="price = Number(price.replace(/[^0-9.-]+/g,''))">
(I should probably put that in the component file, but this illustrates the solution all right).
I hope this can help someone running into a similar issue.
Answered By - nmg49
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.