Angular指令-仅数字和2个小数,逗号分隔

我只允许输入一个输入数字,还可以输入1个逗号和2个小数。

正确输入的示例:

123
123,22

我已经尝试过在网上找到的该指令,但允许我输入以下字符:`,´,+

指令代码:

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

@Directive({
  selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimalNumberDirective {
  // Allow decimal numbers and negative values
  private regex: RegExp = new RegExp(/^\d*\,?\d{0,2}$/g);
  // Allow key codes for special events. Reflect :
  // Backspace,tab,end,home
  private specialKeys: Array<string> = ['Backspace','Tab','End','Home','ArrowLeft','ArrowRight','Del','Delete'];

  constructor(private el: ElementRef) {
  }
  @HostListener('keydown',['$event'])
  onKeyDown(event: KeyboardEvent) {
    console.log(this.el.nativeElement.value);
    // Allow Backspace,and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0,position),event.key == 'Decimal' ? ',' : event.key,current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

此代码有什么问题?

谢谢

b167521 回答:Angular指令-仅数字和2个小数,逗号分隔

只需将您的输入类型编号更改为文本

管道:

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

@Directive({
  selector: '[appDecimalAmount]'
})
export class DecimalAmountDirective {

  private regex: RegExp = new RegExp(/^\d*\,?\d{0,2}$/g);
  private specialKeys: Array<string> = ['Backspace','Tab','End','Home','ArrowLeft','ArrowRight','Del','Delete'];
  constructor(private el: ElementRef) { }
  @HostListener('keydown',['$event'])
  onKeyDown(event: KeyboardEvent) {
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    const current: string = this.el.nativeElement.value;
    const next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();

    }
  }
}

HTML

 <label> Cost (&euro;) <sup class="text-danger">*</sup></label>
  <input type="text" formControlName="predictShippingCost" min="0" appDecimalAmount>
``
本文链接:https://www.f2er.com/2853772.html

大家都在问