Answer the question
In order to leave comments, you need to log in
Entering only numbers?
@Directive({
selector: '[numbersOnly]'
})
export class OnlyNumberDirective {
constructor(private _el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initialValue = this._el.nativeElement.value;
this._el.nativeElement.value = initialValue.replace(/[^0-9]*/g, '');
if ( initialValue !== this._el.nativeElement.value) {
event.stopPropagation();
}
}
}
Answer the question
In order to leave comments, you need to log in
import { Directive } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subscription } from 'rxjs';
@Directive({
selector: '[numbers]',
})
export class NumbersDirective {
sub = new Subscription();
constructor(
private ngControl: NgControl
) { }
ngOnInit() {
this.sub = this.ngControl.valueChanges.subscribe(value => {
this.ngControl.control.setValue(
(value || '').replace(/[^0-9]*/g, ''),
{ emitEvent: false },
)
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question