将输入值转换为FormControl

时间:2018-12-16 19:52:00

标签: angular localization angular-directive angular-pipe

在Angular应用中有一种情况,我需要在控件中接受十进制数字值。问题是它应该接受带逗号或点的数字(作为小数点符号),然后将其转换为正确的格式(例如xxx xxx xxx,yy)。它必须是反应形式的解决方案。到目前为止,我所做的是下面的指令,它可以正常工作,但是我需要将写入的值转换为正确的格式,然后将其传递给绑定的formControl属性。现在它不受影响,当我键入1023.20和1023,20时,没有任何转换,并且我无法在数学运算中使用该值(它们显示NaN值)。有没有办法以角的反应形式实现这种行为?

import { Directive, ElementRef, OnInit, HostListener } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { Logger } from '@app/core';
import { NgControl } from '@angular/forms';

const log = new Logger("DecimalNumberFormatterDirective");

@Directive({
  selector: '[decimalNumberFormatter]',
  providers: [DecimalPipe]
})
export class DecimalNumberFormatterDirective implements OnInit {

  private el: HTMLInputElement;

  private _format: string = "1.2-2";
  private _locale: string = "somelocale";

  constructor(private elementRef: ElementRef, private decimalPipe: DecimalPipe, private control: NgControl) {
    this.el = elementRef.nativeElement;
  }

  ngOnInit(): void {
    this.el.value = this.transformValue(this.el.value);

  }

  @HostListener("change", ["$event", "$event.target.value"])
  onBlur(event: any, value: any) {
    log.debug(value);
    let str = this.parseNumber(value);
    this.el.value = this.transformValue(str);

  }


  transformValue(value: any): string {
    let currency = this.decimalPipe.transform(value, this._format, this._locale);
    return currency.trim();
  }
  parseNumber(str: string): number {
    return parseFloat(str.replace(" ", "").replace(",", "."))
  }
}

0 个答案:

没有答案