Nico Grunfeld
Nico Grunfeld

Reputation: 1133

Ionic 3 Input Percentage Mask

I'd like to hear any advice or recommendation on how to accomplish this. The requirement is to create an input mask directive that only allows the user to enter numbers, optionally 2 decimals, and it also has the % symbol inside the input field. Any idea, or if there is anything already built for this would be very appreciated, thanks in advance!

Upvotes: 2

Views: 3442

Answers (2)

Nico Grunfeld
Nico Grunfeld

Reputation: 1133

following Sam advice, solved with text-mask:

<input type="tel" [(ngModel)]="percent"
[textMask]="{mask: mask, pipe: percentage, guide:false}" />

and..

mask(obj) {
    return [ /\d/, /\d|./, /\d|./, /\d/, /\d/ ];
};

percentage(value) {
    var num = value.replace('%', '');
    if (isNaN(num)) {
        if (num % 1 != 0) {
            num = parseFloat(num).toFixed(2);
        }
        return num + '%';
    } else {
        return false;
    }
}

Upvotes: 0

Sampath
Sampath

Reputation: 65978

Hope you can use text-mask module.

But you need to install Ionic 3 compatible version as shown below.

npm install [email protected] --save

Change package.json as below (i.e. remove ^)

  "angular2-text-mask": "8.0.2",

This module has a lot of features. See the above link.

Update: If you're using Lazy loading then you must import TextMaskModule inside either page's module or shared.module.ts and also you need to set the maxlength on the ion-input to avoid extra character which will appear on blur event.

Upvotes: 4

Related Questions