There must a requirement in any application to allow only entering numbers in text inputs. This can be solved by creating a directive with onKeydown event handler. And then adding this directive to input element. See below code sample.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[allowNumbersOnly]'
})
export class AllowNumbersOnlyDirective {
constructor() {}
/**
* On keydown event handler.
* Here we check if the input is number or not, if not we just ignore the input.
* @param {KeyboardEvent} $event
* @return {boolean}
*/
@HostListener('keydown', ['$event'])
onKeydown($event: KeyboardEvent) {
if (!$event) {
return true;
}
return ($event.keyCode > 95 && $event.keyCode < 106)
|| ($event.keyCode > 47 && $event.keyCode < 58)
|| ($event.keyCode > 36 && $event.keyCode < 41)
|| $event.keyCode === 8;
}
}
We add this directive to input element like below.
<input type="text" allowNumbersOnly class="form-control">
When user tries to enter value other than number we simple ignore the input.
Also don’t forget to add the directive AllowNumbersOnlyDirective to the module declarations.
Few reads: