【问题标题】:Need Angular Directive--Digit number and/or two decimal in the textbox需要 Angular 指令——文本框中的数字和/或两位小数
【发布时间】:2019-11-22 01:06:19
【问题描述】:

我只想在文本框中输入数字。一个数字或带两位小数的数字。 例如,123451234.56

我在网上找到了一些代码,但现在找不到资源。那个只适用于一个数字,但在两位小数上失败。我想修改代码。在这里。

 currencyChars = new RegExp('[\.,]', 'g'); // we're going to remove commas and dots
constructor(public element: ElementRef, public renderer: Renderer2, private decimalPipe: 
DecimalPipe) {}

ngOnInit() {
 this.format(this.element.nativeElement.value);
}

@HostListener('input', ["$event.target.value"]) onInput(e: string) {
  this.format(e);
}

 format(val: string) {
    const numberFormat = parseInt(String(val).replace(this.currencyChars, ''));
    const usdollar = this.decimalPipe.transform(numberFormat, '1.0', 'en-US');
    this.render.setProperty(this.element.nativeElement, 'value', usdollar);
 }

我想我必须更改格式方法。请帮忙。

【问题讨论】:

标签: angular


【解决方案1】:

来自this stackoverflow answer

我们可以改进指令以考虑小数

我们得到改变@Input 的可能小数

  decimales: string = "";
  @Input()
  set mask(value: string) {
    const i = value.indexOf("d{0,");
    if (i > 0) {
      const decimales = +value.substr(i + 4, 1);
      this.decimales = "000000000".substr(0, decimales);
    }
    this.regExpr = new RegExp(value);
  }

我们添加一个@HostListener 模糊

  @HostListener("blur", ["$event"])
  blur($event) {
    if (this.decimales) {
      let item = $event.target;
      let values = item.value.split(".");
      let value =
        values.length > 1
          ? values[0] + "." + (values[1] + this.decimales).substr(0, this.decimales.length)
          : values[0] + "."+this.decimales;
      this.control.control.setValue(value, { emit: false });
    }
  }

working demo

注意:代码按“原样”提供,不提供任何形式的保证

【讨论】:

    【解决方案2】:

    你可以尝试将参数更改为十进制管道

     ...
     const usdollar = this.decimalPipe.transform(numberFormat, '1.1-2', 'en-US');
     ...
    

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多