使用Angular输入格式编号

时间:2018-01-12 11:32:33

标签: angular angular2-forms angular-directive angular-pipe

在Angular中,如何在不更改模型值的情况下格式化显示的输入值?该值必须以千位分隔符显示(FR为' ',EN为',')和小数点分隔符(FR为',',EN为'.'

当后端从数据加载初始化值时,必须格式化输入。

我尝试过这样的事情:

<input class="form-control" name="test"
      [ngModel]="mynumberValue"
      (ngModelChange)="mynumberValue=$event"
      (blur)="someCalculs()"
      required
      NumberFormat
 >

带有指令:

@Directive({ selector: '[NumberFormat]' }) export class NumberDirective implements DoCheck {

    private el: HTMLInputElement;
    private onLoadCheck = false;

    constructor(
        private elementRef: ElementRef,
        private numberPipe: NumberPipe
    ) {
        this.el = this.elementRef.nativeElement;
    }

    ngDoCheck() {
        // check if value is applied on init
        if (this.el.value) {
            if (!this.onLoadCheck) {
                this.el.value = this.numberPipe.transform(this.el.value);
                this.onLoadCheck = true;
            }
        }
    }

    @HostListener('blur', ['$event.target.value'])
    onBlur(value) {
        this.el.value = this.numberPipe.transform(value);
    }

    @HostListener('focus', ['$event.target.value'])
    onFocus(value) {
        this.el.value = this.numberPipe.parseToNumber(value);
    }
}

和管道:

@Pipe({
    name: 'number',
    pure: true
})
export class NumberPipe implements PipeTransform {

    @SessionStorage('user')
    currentUser: User;

    transform(input: any, minPrecision = 2, maxPrecision = 5): string {

        if (isNaN(input) || input === null) {
            return 'N/A';
        }

        return new Intl.NumberFormat(this.currentUser.langKey, {
            minimumFractionDigits: minPrecision,
            maximumFractionDigits: maxPrecision
        }).format(input);
    }

    parseToNumber(input: string) {
        if (this.currentUser.langKey === 'fr') {
            return input.replace(' ', '').replace(',', '.');
        }
        return input.replace(',', '');
    }
}

但是使用这个解决方案,我的模型不会被识别为数字。

有什么想法吗?

0 个答案:

没有答案
相关问题