I want to restrict the user so that he can enter a positive number between 0 to 100. I have created a directive for that. In some use case, I m facing some issues.
In a table, there are text boxes where I need to restrict the user. Scenarios where it's not working: 1. If he uses tab and comes to that textbox, by default numbers are selected and if he types next number it should replace that number.
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>
If the no. is double-digit then in my code because of this line (parseInt(event.target.value.toString() + e.key.toString() , 0 ) > 100 ) it restrict user from typing that no. But if the previous no. is single digit then it allows the user to replace that number. I wanted that even in the first case, on tab selection it should replace the previous number.