Last active
February 23, 2022 15:11
-
-
Save Mustafa-Omran/8e228298b811b15a29a9eede4894bfad to your computer and use it in GitHub Desktop.
Angular - Custom directive to accept only positive numbers within inputs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- keep it as text to hide arrow up and down --> | |
<!-- user can add negative numbers if type number --> | |
<input type="text" positiveNumbers> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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