将输入字段限制为两位小数-Angular 5 [英] Limit input field to two decimal places - Angular 5

查看:261
本文介绍了将输入字段限制为两位小数-Angular 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下

<input type="number" class="form-control" value="" name="cost_price" #name="ngModel" [(ngModel)]="item.cost_price" placeholder="Cost Price"  />

用户键入的位数不能超过2个小数位.

User should not be able to type more that 2 decimal places.

例如,如果用户要输入21.256.应该只允许他输入21.25

For example, if the user wants to enter 21.256. He should be only allowed to enter 21.25

如何使用角度5实现此目标?

How to achieve this using angular 5?

推荐答案

首先创建指令以限制打字稿中的两个小数位,如下所示:

First create Directive for limit the two decimal places in typescript like this:

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
  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) {
    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();
    }
  }
}

app.module.ts中插入指令. 在您的html中使用该指令,如下所示:

Inject Directive in your app.module.ts. In your html use that directive like this:

<input type="textbox" [(ngModel)]="InputValue" appTwoDigitDecimaNumber>

以下是Angular 4/5/6中的工作示例:限制两位小数号码验证

Here is working example in Angular 4/5/6: Limit Two decimal places number validation

希望这对您有帮助!!!!

Hope this will help you!!!!

这篇关于将输入字段限制为两位小数-Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆