February 16, 2017 · ionic

MaskMoney no Ionic 2

Solução alternativa para mascarar o input de um campo monetário no Ionic 2 no padrão: NNNN.NN ("cents to dollar")

Classe:

// util.ts
import {Injectable} from '@angular/core';

@Injectable()
export class Utils {
  private n: any;
  private len: any;

  detectAmount(v): string {
    if (v) {
      this.n = v[v.length - 1];
      if (isNaN(this.n)) {
        v = v.substring(0, v.length - 1);
        return v;
      }
      v = this.fixAmount(v);
      return v;
    }
  }

  private fixAmount(a): string {
    let period = a.indexOf(".");
    if (period > -1) {
      a = a.substring(0, period) + a.substring(period + 1);
    }
    this.len = a.length;
    while (this.len < 3) {
      a = "0" + a;
      this.len = a.length;
    }
    a = a.substring(0, this.len - 2) + "." + a.substring(this.len - 2, this.len);
    while (a.length > 4 && (a[0] == '0')) {
      a = a.substring(1)
    }
    if (a[0] == ".") {
      a = "0" + a;
    }
    return (a);
  }
}

Injeta ele no seu Module:

// app.module.ts
import {MyApp} from './app.component';
import {Utils} from './utils';

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    IonicModule.forRoot(MyApp, {
      backButtonText: 'Voltar'
    })
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
    {
      provide: ErrorHandler,
      useClass: IonicErrorHandler
    },
    Utils
  ]
})
export class AppModule {
}

No HTML..

<ion-input type="tel" [(ngModel)]="amount" (keyup)="amountChange()" placeholder="0.00"></ion-input>

E use no Component:

(...)
import {Utils} from "../../app/utils";
(...)

///

export class MyComponent {
  this.amount: string;

  constructor(private utils: Utils) { }

  amountChange() {
    this.amount = this.utils.detectAmount(this.amount);
  }
}

Transforma os valores do ion-input nessa forma:
12345 = 123.45
30 = 0.30
5 = 0.05
e assim vai..

Testado no iOS10 (device) e Android 7.0 (emulator) com Ionic 2.

Meu ionic info:

Your system information:

Cordova CLI: 6.5.0 
Ionic Framework Version: 2.0.1
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.0.0
ios-deploy version: 1.9.1 
ios-sim version: 5.0.13 
OS: OS X El Capitan
Node Version: v4.6.0
Xcode version: Xcode 8.2.1 Build version 8C1002

Créditos: http://jsbin.com/heqeduyi/1/edit?html,output

Comments powered by Disqus