When we want to format a tag in Angular2 as a currency we use the Pipe Currency:
<p>{{cantidad | currency}}</p>
That works perfectly, but if what we want is for the user to enter an amount of money in an input, how do we make it format correctly?
What you would want is something like this (this example does NOT work of course):
<input [(ngModel)]="cantidad | currency"></ion-input>
And the expected behavior would be that even if the user types "10.2", when the input loses focus on the input we see "€10.20" and in the model we have "10.2".
Note: I know that I could separate [ngModel]="amount" on the one hand and handle the event (change) or the (ngModelChange) on the other hand, but I was looking for a more elegant and comfortable solution.
Thank you very much
Don't use
[(ngModel)]
. Instead use the event(change)
and the attribute[value]
to manually control the value.In your component you should then have something like this
You're basically binding the value of the input to a variable in your component that you manually update every time there's a change in the control. You update the value right after the user finishes typing.
It is recommended that you use the functions that are included in Angular for handling currencies using internationalization, since in all cultures the position of the currency does not go in the same place.
Better do a validation that checks that it is of type currency or that it contains two decimals before saving it to avoid problems when converting it. Otherwise you will have to change the format in the component logic and add the decimals if you are passed an integer.
First of all, I recommend Angular's reactive forms , as they allow you to carry logic and handle state changes on the component side, rather than within the HTML.
If you want to continue using ngModel, it is best to make one
CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR
in the form of a directive called currencyMask, and inside the directive you subscribe to the eventsonBlur
andonFocus
through@HostListener
. For example:It is more tedious, although it allows you to have a Number as a value in the component and modify the "facade" of the value. So when you focus you remove all formatting, and when you blur, you format it to look how you want, without changing your model to an invalid value.
This is basically what https://github.com/cesarrew/ng2-currency-mask does , for example.
modify the ngModel in the tag to be able to use the pipe