Angular6 - 自定义输入字段

Angular6 - Custom Input field

我必须在 Angular 中创建输入字段,该输入字段只允许带 2 位小数的数字,例如 '123455.12'

以下是我目前尝试过的方法

<input myCustomDirective type="text">

我创建了指令。在我的 CustomDirective 中,我在该侦听器中使用 HostListener 作为按键事件,我使用正则表达式进行验证,但它只允许数字,不允许输入 '.(dot)'

new RegExp('^[0-9]*$');//我的正则表达式

请查看 fiddle jsfiddle.net/gsferreira/Lsv9f0b0 ,张贴在 link , ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" 是关键

来自 Plain Old Java 脚本 fiddle link https://jsfiddle.net/j3cbytws/

请只输入数字,并允许使用一个点,其他不能:

<input type="number" name="someid" onkeypress="return isNumberKey(event)" /> 

<script>
var isDecimalAlredyEcountered = false;
function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if(isDecimalAlredyEcountered && charCode === 46)
    return false;
   if(charCode == 46)
    {isDecimalAlredyEcountered =true;
    }
    if (charCode > 31 && (charCode < 48 || charCode > 57)&& charCode != 46)
        return false;
    return true;
}    
</script>

上述实现可能存在退格字符和删除问题,因此您必须在清除时重置状态

ng-pattern 你要求的是 ng-pattern=" /^[.\d]+$/"

Here's a Directive that takes Only Decimal Values with custom precisions.

https://stackblitz.com/edit/angular-decimal-directive

  • 它将允许您在 .(点)之前放置数字
  • 不允许粘贴 (ctrl+v) non-decimal.
  • 需要单个.(点)。默认情况下,它会在 . 之后占用 2 位数字。 (点).

示例:

`<input type="text" [(ngModel)]="myVar" decimal>`

但是你可以这样定义精度大小:-

`<input type="text" [(ngModel)]="myVar" [decimal]="3">`
  • 如果你只想使用整数而不是浮点数,你可以使用这样的指令:

    <input type="text" [(ngModel)]="myVar" [decimal]="0">

  • 如果你在输入中没有完成足够的精度,那么它将 自动完成其余数字精度(如果是 .(点) 需要)通过 onblur 事件。

  • 您不能通过双向绑定注入字符串值。

N.B:[(ngModel)] 是使用指令所必需的。