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

在模板中使用该指令:


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

相关内容

热门资讯

外挂方案!智星菠萝透视,pok... 外挂方案!智星菠萝透视,pokerworld破解版下载-确实一直都是有辅助攻略(哔哩哔哩)亲,关键说...
外挂法门!werplan辅助软... 外挂法门!werplan辅助软件,来玩德州破解器-一直存在有辅助教程(哔哩哔哩)暗藏猫腻,小编详细说...
外挂讲义!德州辅助工具到底怎么... 外挂讲义!德州辅助工具到底怎么样,impoker辅助-原来存在有辅助插件(哔哩哔哩)1)德州辅助工具...
外挂操作!poker worl... 外挂操作!poker world辅助,哈糖大菠萝万能挂-确实一直总是有辅助技巧(哔哩哔哩)1、在哈糖...
外挂指引!哈糖大菠萝挂,红龙p... 外挂指引!哈糖大菠萝挂,红龙poker辅助平台-确实存在有辅助方法(哔哩哔哩)一、红龙poker辅助...
外挂经验!xpoker辅助控制... 外挂经验!xpoker辅助控制,xpoker透视辅助-原来一直总是有辅助工具(哔哩哔哩);1、用户打...
外挂演示!约局吧辅助器,agp... 外挂演示!约局吧辅助器,agpoker辅助-一直一直都是有辅助教程(哔哩哔哩)1、约局吧辅助器免费脚...
外挂课程!拱趴大菠萝开挂方法,... 外挂课程!拱趴大菠萝开挂方法,pokerrrr2辅助-确实存在有辅助工具(哔哩哔哩)暗藏猫腻,小编详...
外挂模板!uupoker有透视... 外挂模板!uupoker有透视吗,约局吧开挂神器是真的吗-一直真的是有辅助方法(哔哩哔哩)1、约局吧...
外挂教材!佛手在线大菠萝辅助,... 外挂教材!佛手在线大菠萝辅助,拱趴大菠萝万能辅助器-都是是真的有辅助攻略(哔哩哔哩)外挂教材!佛手在...