Skip to content

Instantly share code, notes, and snippets.

@Mustafa-Omran
Last active February 23, 2022 15:11
Show Gist options
  • Save Mustafa-Omran/8e228298b811b15a29a9eede4894bfad to your computer and use it in GitHub Desktop.
Save Mustafa-Omran/8e228298b811b15a29a9eede4894bfad to your computer and use it in GitHub Desktop.
Angular - Custom directive to accept only positive numbers within inputs
<!-- keep it as text to hide arrow up and down -->
<!-- user can add negative numbers if type number -->
<input type="text" positiveNumbers>
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[positiveNumbers]'
})
export class PositiveNumbersDirective {
private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
private specialKeys: Array<string> = ['Backspace', 'Tab'];
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PositiveNumbersDirective } from './positive-numbers.directive';
@NgModule({
declarations: [
PositiveNumbersDirective
],
imports: [
CommonModule
],
exports: [
PositiveNumbersDirective
]
})
export class PositiveNumbersModule { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment