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

在模板中使用该指令:


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

相关内容

热门资讯

透视数据!pokerrrr2辅... 透视数据!pokerrrr2辅助,wepoker私人局怎么玩,学习教程(一贯是真的挂)-哔哩哔哩1、...
透视透视挂!wepoker怎么... 透视透视挂!wepoker怎么提高运气,欢乐达人暗堡链接辅助,一直真的有挂(专业力荐教程)-哔哩哔哩...
透视检测!aa poker辅助... 透视检测!aa poker辅助包(透视)开挂辅助技巧(原来真的是有挂)-哔哩哔哩1、aa poker...
透视工具!pokemmo脚本辅... 透视工具!pokemmo脚本辅助下载,德扑之心免费透视,学习教程(一直存在有挂)-哔哩哔哩1)pok...
透视ai代打!wepoker轻... 透视ai代打!wepoker轻量版有透视吗,牵手游戏辅助,一贯是有挂(了解必备教程)-哔哩哔哩暗藏猫...
透视规律!wepoker有用吗... 透视规律!wepoker有用吗(透视)开挂辅助器(切实真的是有挂)-哔哩哔哩透视规律!wepoker...
透视挂!pokerworld破... 透视挂!pokerworld破解版下载,哈糖大菠萝破解器,秘籍教程(确实真的有挂)-哔哩哔哩1、不需...
受玩家影响!aapoker插件... 受玩家影响!aapoker插件,白银胡乐辅助脚本最新版安装方法,本来有挂(关于必备教程)-哔哩哔哩亲...
透视稳定!pokemmo辅助器... 透视稳定!pokemmo辅助器手机版下载(透视)开挂辅助技巧(其实存在有挂)-哔哩哔哩1)pokem...
透视好牌!wepoker开辅助... 透视好牌!wepoker开辅助能查到吗,wepokerplus脚本,教材教程(果然存在有挂)-哔哩哔...