Reputation: 1450
I am trying to write code which will allow only numbers in a text input text. I've written the following directive.
import { Directive, ElementRef, Input, HostListener } from '@angular/core'
@Directive({
selector: '[appAllowNumberonly]'
})
export class AllowNumberonlyDirective {
private el: HTMLInputElement;
constructor(private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
@HostListener("keydown", ["$event"])
onKeyDown(e: KeyboardEvent) {
if (this.el.value == undefined) {
this.el.value = '';
}
let transformedInput = this.el.value.replace(/[^0-9]/g, '');
if (transformedInput != this.el.value) {
this.el.value = transformedInput;
}
}
@HostListener("keyup", ["$event"])
onKeyUp(e: KeyboardEvent) {
if (this.el.value == undefined) {
this.el.value = '';
e.preventDefault();
}
let transformedInput = this.el.value.replace(/[^0-9]/g, '');
if (transformedInput != this.el.value) {
this.el.value = transformedInput;
}
return transformedInput;
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
if (this.el.value == undefined) {
this.el.value = '';
}
let transformedInput = this.el.value.replace(/[^0-9]/g, '');
if (transformedInput != this.el.value) {
this.el.value = transformedInput;
}
}
}
This works perfectly fine, but user is able to enter value into the text box and then my directive is removing the values that are non-numeric, but I want to stop user from entering into the textbox, how can I achieve that?
I want to cover copy paste scenario with mouse as well.
I have below Plunker which works perfectly fine in AngularJS (1.x), how do I convert to Angular? I am unable to use parsers.
http://jsfiddle.net/thomporter/DwKZh/
I also tried this:
Upvotes: 2
Views: 11837
Reputation: 1619
Try this directive. Listen for the input event to also handle copy and paste.
export class NumberOnlyDirective {
constructor(private el: NgControl) {}
@HostListener('input', ['$event.target.value'])
onInput(value: string) {
// NOTE: use NgControl patchValue to prevent the issue on validation
this.el.control.patchValue(value.replace(/[^0-9]/g, ''));
}
}
Upvotes: 6
Reputation: 71
You can use Ng Knife utility
Import NgKnifeModule
...
import { NgKnifeModule } from 'ng-knife';
...
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
NgKnifeModule
],
...
});
export class AppModule { }
Using it:
<!-- Only Numbers -->
<input knifeOnlyNumbers type="text">
Upvotes: 6
Reputation: 834
your directive code should have this
@HostListener("keypress",['$event']) onKeyPress(e){
var char=e.char;
var regExp = new RegExp(/[0-9.]/);
if (regExp.test(char))
return true
else
return false;
}
Upvotes: 0