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

时间:2017-07-27 06:40:29

标签: angular directive

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

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

2 个答案:

答案 0 :(得分:3)

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

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">

答案 1 :(得分: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 || (value === '' && this._elementRef.nativeElement.value==='$0')) {
        if ((value === '' && this._elementRef.nativeElement.value==='$0') && !this._restStage) {
            this._restStage = true;
            this._elementRef.nativeElement.value = null;
            this._model.control.setValue(null);
            return;
        }
        this._restStage = false;
    });

   }
}
相关问题