As a long-term user of the InputMask plugin, I’ve long put up with its downsides such as issues around negative amounts and decimals.
Recently, I was tasked with integrating Autonumeric into an Aurelia application at work and the result was simple and elegant, I thought I would share it.
The result works out a lot nicer than InputMask which I personally find to be an absolute nightmare to work with for currency scenarios especially.
Install Dependencies
We will be using the autonumeric
plugin as well as lodash
for this one. You can replace the Lodash dependency with your own solution if you like.
npm install autonumeric lodash
Create The Component
Create a new file called auto-numeric.ts
and add in the following. This is the view-model for our custom element.
import { customElement, bindingMode } from 'aurelia-framework'; import AutoNumeric from 'autonumeric'; import { bindable } from 'aurelia-framework'; import merge from 'lodash/defaultsDeep'; // Equivalent of setting 'dollar' as the secondary config option for the plugin const defaultOptions = { digitGroupSeparator : ',', decimalCharacter : '.', currencySymbol : '$', currencySymbolPlacement : 'p', negativePositiveSignPlacement: 'r' }; @customElement('auto-numeric') export class IaNumeric { private im; private input: HTMLInputElement; @bindable({ defaultBindingMode: bindingMode.twoWay }) value; @bindable() options; constructor(private element: Element) { } attached() { this.im = new AutoNumeric(this.input, merge(this.options, defaultOptions)); this.im.set(this.value); this.element.addEventListener('autoNumeric:rawValueModified', this.rawValueChanged); } detached() { this.element.removeEventListener('autoNumeric:rawValueModified', this.rawValueChanged); } rawValueChanged = () => { this.value = this.im.getNumber(); } optionsChanged() { if (this.im) { this.im.update(merge(this.options, defaultOptions)); } } }
Now, create a view for our custom element auto-numeric.html
<template> <input type="text" ref="input" one-time.bind="value"> </template>
Usage
To use the plugin, make sure you import it and then you reference it like any normal input. Now, the value going in doesn’t override the input when you type into it, we only care about the value coming out.
<auto-numeric value.bind="myVar"></auto-numeric>