I am trying to make a inputNumber directive which will prevent typing (not highlighting the input when value is wrong, but even typing in wrong value):
a) letters and symbols, restrict only to [0-9] b) respect min and max params c) be in relation with other such directives in the view via greaterOrEqual / lessOrEqual properties.
This is my input-number.directive.ts:
import {Directive, HostListener, Input} from '@angular/core'; @Directive({ selector: '[inputNumber]' }) export class InputNumberDirective { @Input() min: number = 0; // will be input @Input() max: number = 100; // will be input @Input() greaterOrEqual: number = 23; // will be input @Input() lessOrEqual: number = 77; // will be input @HostListener('keypress', ['$event']) sanitizeValue(event: KeyboardEvent): boolean { const targetVal: number = Number((<HTMLInputElement>event.target).value); if (event.charCode >= 48 && event.charCode < 58) { if (this.min !== null && targetVal < this.min) { return false; } if (this.max !== null && targetVal > this.max) { return false; } if (this.greaterOrEqual !== null && targetVal < this.greaterOrEqual) { return false; } return !(this.lessOrEqual !== null && targetVal > this.lessOrEqual); } return false; } } This all works in terms of preventing typing letters/symbols, but when it comes to respecting numbers limiters user is still able to type them over and my purpose to prevent this. I found some SO threads (e.g. Don't allow typing numbers between max and min value) on this, but it didn't help me a lot.