用户键入时将输入字段值格式化为货币

Format input field value as a currency when user types

我对文本字段有以下要求。当用户开始输入他的输入时,它的格式应该如下所示

0.00 (Start)
0.01
0.12
1.23
12.34
123.45
1,234.56
12,345.67
123,456.78

我使用下面的货币掩码,效果很好,但我无法将字段设为空,即用户无法清空文本框。该指令默认将值设置为 0.0。我可以覆盖指令,以便用户也可以将框留空吗?或任何其他做同样事情的指令?我正在使用 Angular 4 个项目

https://www.npmjs.com/package/ng2-currency-mask

我认为这应该有所帮助,我也在 plunker 上使用最新的 ng2-currency-mask@4.2.0 进行了测试,一切似乎都运行良好。

import { Directive, ElementRef } from '@angular/core';
import { NgModel } from '@angular/forms';

@Directive({
    selector: '[appZero]'
})
export class AppZeroDirective {

    private _restStage: boolean = false;

    constructor(
        private _model: NgModel,
        private _elementRef: ElementRef
    ) {

        this._model.control.valueChanges.subscribe((value: any) => {
            if ((value === null || value === 0) && !this._restStage) {
                this._restStage = true;
                this._elementRef.nativeElement.value = null;
                this._model.control.setValue(null);
                return;
            }
            this._restStage = false;
        });

    }
}

像这样将 [appZero] 指令应用于您的输入:

<input appZero currencyMask [(ngModel)]="value">

试试这个

import { Directive, ElementRef } from '@angular/core';
import { NgModel } from '@angular/forms';

@Directive({
selector: '[appZero]'
})
export class AppZeroDirective {

private _restStage: boolean = false;

constructor(
    private _model: NgModel,
    private _elementRef: ElementRef
) {

    this._model.control.valueChanges.subscribe((value: any) => {
      //  if ((value === null || value === 0) && !this._restStage || (value === '' && this._elementRef.nativeElement.value==='[=10=]')) {
        if ((value === '' && this._elementRef.nativeElement.value==='[=10=]') && !this._restStage) {
            this._restStage = true;
            this._elementRef.nativeElement.value = null;
            this._model.control.setValue(null);
            return;
        }
        this._restStage = false;
    });

   }
}