Ionic natively doesn’t provide any graceful input component for capturing user input for currency or decimal data (with defined precision and separator).
With native <ion-input>, capturing user input in decimal format can get ugly, prone to validation errors, and of course not a great user experience.
<ion-input placeholder="$0.00" inputmode="decimal" [(ngModel)]="entry" name="amount"></ion-input>
As we see here, with no input restrictions & validations, obvious difference in what we expected and what we got, that’s a hell of a creative user.
There are a couple of solution packages available, which helps you get the desired result to some extent:
but nothing fits right & meet the expectation truly. It adds more complexity to a simple problem, and yet not providing 100% satisfaction.
Angular does provide a currency pipe for a formatted display of amount, which is very useful but doesn’t help with capturing input.
Here is my pretty, efficient & simple solution to a very common use case of currency input, by combining the power of angular data binding, angular currency pipe & native ion-input.
First, we will create a reusable input component:
- The component expects precision & initial amount from the caller page and outputs user entered/modified raw data.
- Inside the component, ion-item encapsulates string field `formattedAmount` to display currency formatted value and ion-input to capture user input.
- By handling both events ionInput & keyup of ion-input, we are first deriving the formattedAmount field using currency pipe and simultaneously clean slating the input box respectively at each keystroke of the user. Of course, ignoring any non-numeric keyboard input. This creates the illusion of a pretty formatted currency input box.
- To help illudes the display text & input box as one entity, trigger the ion-input focus on click of the ion-item.
- Using the EventEmitter to output the raw user input to the calling parent page.
Then, we will use it across any page where user input for the amount in currency format is required:
- Pass the required precision & initial amount.
- Listen to the output event to capture the raw data for calculation.
And, the result is most desired:
I hope you liked ❤️ this article, stay tuned for more posts. All feedback, comments & questions are welcomed. 🏳️🌈
Complete source code is available on Github.
You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…
If this helped you reduce time to develop, you can buy me a cup of coffee ☕