简体   繁体   English

Angular 指令 - 只有数字和 2 位小数,用逗号分隔

[英]Angular directive - Only digits and 2 decimals with comma separated

I need to allow to only write in an input numbers and optionally 1 comma and 2 decimals.我需要只允许写入输入数字和可选的 1 个逗号和 2 个小数。

Example of right inputs:正确输入示例:

123
123,22

I've tried this directive I found online but it's allowing me to enter these characters: `, ´, +我已经尝试过我在网上找到的这个指令,但它允许我输入这些字符:`、´、+

Directive code:指令代码:

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, tab, end, 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();
    }
  }
}

What's wrong with this code?这段代码有什么问题?

Thanks谢谢

JUST CHANGE YOUR INPUT TYPE NUMBER TO TEXT只需将您的输入类型编号更改为文本

pipe:管道:

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 HTML

 <label> Cost (&euro;) <sup class="text-danger">*</sup></label>
  <input type="text" formControlName="predictShippingCost" min="0" appDecimalAmount>
``

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM