Search code examples
angulartypescriptangular2-formsionic3

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!


Solution

  • 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;
        }
    }