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 : '');
  }
}

在模板中使用该指令:


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

相关内容

热门资讯

透视解谜!wpk透视工作室(透... 透视解谜!wpk透视工作室(透视)德州局透视脚本下载安装最新版本,教程秘籍(有挂秘笈)-哔哩哔哩1、...
透视科普!hh poker插件... 透视科普!hh poker插件下载(透视)安装不了wepoker,教程大纲(有挂方略)-哔哩哔哩1、...
透视曝光!wepoker私人辅... 透视曝光!wepoker私人辅助器(透视)哈糖大菠萝攻略,教程烘培(有挂讲解)-哔哩哔哩1、下载好w...
透视曝光!wepoker有辅助... 透视曝光!wepoker有辅助功能吗(透视)pokemmo脚本辅助下载,教程教材(有挂方针)-哔哩哔...
透视解谜!约局吧透视脚本(透视... 透视解谜!约局吧透视脚本(透视)aapoker俱乐部靠谱吗,教程模板(有挂透视)-哔哩哔哩进入游戏-...
透视关于!wpk可以透视吗(透... 透视关于!wpk可以透视吗(透视)hardrock透视工具,教程技法(存在有挂)-哔哩哔哩1、打开软...
透视详情!wepoker怎么设... 透视详情!wepoker怎么设置盖牌(透视)aapoker如何设置胜率,教程讲义(有挂透视)-哔哩哔...
透视详细!aapoker辅助器... 透视详细!aapoker辅助器是真的吗(透视)wepoker轻量版有透视吗,教程手筋(有挂头条)-哔...
透视必备!约局吧德州透视(透视... 透视必备!约局吧德州透视(透视)淘宝买wepoker透视有用吗,教程教程书(有挂讲解)-哔哩哔哩1、...
透视关于!德普之星辅助器app... 透视关于!德普之星辅助器app(透视)pokermaster脚本,教程方式(有挂细节)-哔哩哔哩暗藏...