How to get an input to display and edit currency with angular 4 pipes

Issue

My goal is to have an input field that allows the user to edit a number as currency. E.g. The user sees “$1,000”, they can type a ‘0’, and the edit box shows “$10,000”. And the resulting data model is a number 10000.

<input type="text" name="Data" [ngModel]="Data | currency:'USD':true:'4.0-0'" (ngModelChange)="Data=$event" >

The above displays in the edit box ‘$1,000’, but when I edit the value in the input box, the value is no longer a number 1000, it is a string “$1,000”. Meaning my data model went from

{ myCost: 1000 } 

to become

{ myCost: "$1,000" }

Any ideas on the correct way to do this? It’s looking like I need to create a new function to convert from currency back to number. Which is possible, but it seems like there is a better way.

Solution

You can handle ngModelChange in your component class
(ngModelChange)="onInputValueChange($event)"

In component.ts
onInputValueChange(newValue: any):Number {
return <Number>newValue;
}

Answered By – Ankit Kapoor

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.