Input mask with thousand separator ionic 3

♀尐吖头ヾ 提交于 2019-12-08 02:29:14

问题


I need a thousand separator input mask directive or else with Ionic 3 app. I have tried 2 directives. But none of them were working. Do you know working directive for that?

e.g. 50,000

.html

<ion-input type="tel" [ngModel]="data?.budget" formControlName="budget" (ngModelChange)="data.budget=$event"></ion-input>

I have logged issues on Git. please see that too:

text-mask Issue

ng2-currency-mask Issue


回答1:


Here is my version of formatting that works on ionic too.

Typescript:

format(valString) {
    if (!valString) {
        return '';
    }
    let val = valString.toString();
    const parts = this.unFormat(val).split(this.DECIMAL_SEPARATOR);
    return parts[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, this.GROUP_SEPARATOR) + (!parts[1] ? '' : this.DECIMAL_SEPARATOR + parts[1]);
};

unFormat(val) {
    if (!val) {
        return '';
    }
    val = val.replace(/^0+/, '');

    if (this.GROUP_SEPARATOR === ',') {
        return val.replace(/,/g, '');
    } else {
        return val.replace(/\./g, '');
    }
};

HTML:

<ion-input [(ngModel)]="budget"  pattern="^[$\-\s]*[\d\,]*?([\.]\d{0,10})?\s*$"
style="border:1px solid black" #myBudget="ngModel" (input)="budget = format(budget)"></ion-input>
<p style="color:red" *ngIf="myBudget.errors && myBudget.errors?.pattern">Enter numbers only</p>

It need some improvements in error management and currency addition (it accepts leading '$' sign). I set the regexp to accept numbers with 10 decimals.

DEMO

If you wish no decimals and only numeric input, this DEMO shows how.



来源:https://stackoverflow.com/questions/46189208/input-mask-with-thousand-separator-ionic-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!