我想限制用户,以便他可以输入0到100之间的正数。为此我创建了一条指令。在某些用例中,我遇到了一些问题。
在表中,有一些文本框需要限制用户。无法运作的情况: 1.如果他使用制表符并转到该文本框,则默认情况下会选择数字,并且如果他键入下一个数字,则应替换该数字。
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[appInputRestriction]'
})
export class InputRestrictionDirective {
inputElement: ElementRef;
isFocused: boolean;
@Input('appInputRestriction') appInputRestriction: string;
arabicRegex = '[\u0600-\u06FF]';
constructor(el: ElementRef) {
this.inputElement = el;
}
@HostListener('keydown', ['$event']) onkeydown(event) {
if (this.appInputRestriction === 'integer') {
this.integerOnly(event);
}
}
integerOnly(event) {
const e = <KeyboardEvent>event;
if (e.key === 'Tab' || e.key === 'TAB') {
return;
}
if ([8, 9, 27, 13, 110].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode === 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode === 67 && e.ctrlKey === true) ||
// Allow: Ctrl+V
(e.keyCode === 86 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode === 88 && e.ctrlKey === true)) {
// let it happen, don't do anything
return;
}
if ( ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'].indexOf(e.key) === -1 ||
parseInt(event.target.value.toString() + e.key.toString() , 0 ) > 100 ) {
e.preventDefault();
}
}
//html code
<td class="number-cell editable">
<input
[ngModel]="t.timePct"
(ngModelChange)="t.timePct = $event; t.isDirty = true"
type="number"
(input)="this.calculateTotals()"
autocomplete="off"
appInputRestriction="integer"
min="0"
max="100"
/>
</td>
如果没有。是两位数,然后在我的代码中由于此行(parseInt(event.target.value.toString()+ e.key.toString(),0)> 100)限制了用户键入该编号。但是如果以前没有。是一位数字,则它允许用户替换该数字。我希望即使在第一种情况下,在选项卡选择上也应替换先前的数字。