我有一个场景,我应该在Angular 2/4/5中限制一个带有2个小数位的输入框。我应该为此写一个指令吗?
示例:12.25,14524.21,12547896324.01
我们不应该允许用户在完成两个小数值后输入额外的击键次数
答案 0 :(得分:1)
我宁愿使用Validator:
this.myReactiveForm = this._formBuilder.group({
myNumber: ['', [Validators.pattern(/^\d*(?:[.,]\d{1,2})?$/)]]
});
答案 1 :(得分:0)
<label>Enter value</label> <br/>
<input type="text" name="test" placeholder="00.00" [(ngModel)]="textValue" appIsDecimal>
ng g d IsDecimalDirective
创建指令在IsDecimalDirective文件中,将以下代码写入
import { Directive, ElementRef, HostListener, Input, forwardRef, Attribute, AfterContentInit, OnChanges, OnDestroy } from '@angular/core';
import { NG_VALIDATORS, AbstractControl, ValidatorFn, Validator, FormControl, NgModel } from '@angular/forms';
@Directive({
selector: '[IsDecimal]'
})
export class IsDecimalDirective {
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) {
// 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();
}
}
}