2017-02-07 3 views
1

入力時に入力を米ドルの通貨にフォーマットしたいとします。入力は小数点以下2桁で、右から左に入力されます。 54.60と入力すると、$ 0.05 - > $ 0.54 - > $ 5.46 - > $ 54.60と入力されたとします。このPLUNKERはこれを正確に行いますが、角度jで表します。更新角度2で書式通貨を入力

<input name="cost" placeholder="cost" class="form-control" type="text" currency formControlName="cost" (rawChange)="rawCurrency=$event"> 

何最後に私のために働いたことは次のとおりです。

onInputChange(event: any, backspace: any) { 
    var newVal = (parseInt(event.replace(/[^0-9]/g, ''))/100).toLocaleString('en-US', { minimumFractionDigits: 2 }); 
    var rawValue = newVal; 

    if(backspace) { 
     newVal = newVal.substring(0, newVal.length - 1); 
    } 

    if(newVal.length == 0) { 
     newVal = ''; 
    } 
    else { 
     newVal = newVal; 
    } 
    // set the new value 
    this.model.valueAccessor.writeValue(newVal); 
    this.rawChange.emit(rawValue) 
    } 
これまでのところ、私のディレクティブは次のようになります。

import {Directive, Output, EventEmitter} from '@angular/core'; 
import {NgControl} from '@angular/forms'; 

@Directive({ 
    selector: '[formControlName][currency]', 
    host: { 
    '(ngModelChange)': 'onInputChange($event)', 
    '(keydown.backspace)':'onInputChange($event.target.value, true)' 
    } 
}) 
export class CurrencyMask { 
    constructor(public model: NgControl) {} 

    @Output() rawChange:EventEmitter<string> = new EventEmitter<string>(); 

    onInputChange(event: any, backspace: any) { 
    // remove all mask characters (keep only numeric) 
    var newVal = event.replace(/\D/g, ''); 
    var rawValue = newVal; 
    var str = (newVal=='0'?'0.0':newVal).split('.'); 
    str[1] = str[1] || '0'; 
    newVal= str[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,') + '.' + (str[1].length==1?str[1]+'0':str[1]); 



    // set the new value 
    this.model.valueAccessor.writeValue(newVal); 
    this.rawChange.emit(rawValue) 
    } 
} 

とhtmlにそれはとして使用されています

+0

ご質問ありがとうございますか? – Blauhirn

+0

私は、指定されたPLUNKERがアンギュラ2で行っていることを実行したいのですが、右から左へ入力を入力してフライでフォーマットするには – Jane

答えて

0

入力を変更すると、次のようになります

唯一

var newVal = (parseInt(myVal.replace(/\.,/g, ''))/100) 

を使用してUSD形式にフォーマットする

// remove dot and comma's, 123,456.78 -> 12345678 
var strVal = myVal.replace(/\.,/g,''); 
// change string to integer 
var intVal = parseInt(strVal); 
// divide by 100 to get 0.05 when pressing 5 
var decVal = intVal/100; 
// format value to en-US locale 
var newVal = decVal.toLocaleString('en-US', { minimumFractionDigits: 2 }); 

// or in singel line 
var newVal = (parseInt(myVal.replace(/\.,/g, ''))/100).toLocaleString('en-US', { minimumFractionDigits: 2 }); 

または

使用通貨パイプは、この情報がお役に立てば幸いです。

+0

タイプ1の場合、 ;私は8を入力すると0になります。これはこのように動作し続けます – Jane

+0

イベントから文字を取得していると仮定します。この場合、strValの最後に新しいcharを追加する必要があります。 (もちろんこれは私の意見です)angle2での双方向バインディングを使用して、入力がngModelで更新され、各キー押下後にその変数を更新することです。 – hakany

+0

var newVal =(parseInt(myVal.replace(/\.,/) g、 '')+ newChar)/ 100).toLocaleString( 'en-US'、{minimumFractionDigits:2}); – hakany