Angular指令 - 只允许输入数字和两位小数,以逗号分隔
创始人
2024-10-30 22:30:18
0

可以使用Angular的自定义指令来实现只允许输入数字和两位小数,以逗号分隔的功能。下面是一个示例代码:

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

@Directive({
  selector: '[appNumberFormat]'
})
export class NumberFormatDirective {

  constructor(private el: ElementRef) { }

  @HostListener('input', ['$event'])
  onInputChange(event: any) {
    const initialValue = this.el.nativeElement.value;
    let newValue = initialValue.replace(/[^0-9.,]/g, ''); // 只允许数字、逗号和句点
    newValue = this.formatNumber(newValue); // 格式化数字

    if (initialValue !== newValue) {
      this.el.nativeElement.value = newValue;
      event.stopPropagation();
    }
  }

  private formatNumber(value: string): string {
    const parts = value.split('.');
    const integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); // 每三位数字加一个逗号

    let decimalPart = '';
    if (parts.length > 1) {
      decimalPart = parts[1].substring(0, 2); // 只保留两位小数
    }

    return integerPart + (decimalPart ? '.' + decimalPart : '');
  }
}

在模板中使用该指令:


这样,输入框就只能输入数字、逗号和句点,并且会自动格式化为每三位数字加一个逗号的形式,保留两位小数。

相关内容

热门资讯

透视挂透视!aapoker能控... 透视挂透视!aapoker能控制牌吗(透视)透视插件(好像有挂)aapoker能控制牌吗辅助器中分为...
透视透视!aapoker透视插... 透视透视!aapoker透视插件(透视)透视方法(总是存在有挂)1、每一步都需要思考,不同水平的挑战...
透视最新!aapoker发牌逻... 透视最新!aapoker发牌逻辑(透视)ai插件(都是是真的有挂);所有人都在同一条线上,像星星一样...
透视科技!aapoker透视脚... 透视科技!aapoker透视脚本入口(透视)透视方法(竟然真的是有挂)1、首先打开aapoker透视...
透视数据!aapoker插件下... 透视数据!aapoker插件下载(透视)透视脚本下载(竟然是有挂)1、首先打开aapoker插件下载...
透视透视!aapoker破解侠... 透视透视!aapoker破解侠是真的吗(透视)发牌逻辑(竟然是真的有挂);aapoker破解侠是真的...
辅助透视!aapoker辅助怎... 辅助透视!aapoker辅助怎么用(透视)透视脚本(一贯真的是有挂)进入游戏-大厅左侧-新手福利-激...
透视安装!aapoker辅助器... 透视安装!aapoker辅助器怎么用(透视)透视脚本入口(原来有挂)1、aapoker辅助器怎么用a...
透视辅助!aapoker透视方... 透视辅助!aapoker透视方法(透视)插件下载(一贯是真的有挂)透视辅助!aapoker透视方法(...
透视攻略!aapoker能控制... 透视攻略!aapoker能控制牌吗(透视)辅助插件工具(原来是真的有挂);小薇(透视辅助)致您一封信...