Skip to content

Instantly share code, notes, and snippets.

@raco
Created May 15, 2024 23:29
Show Gist options
  • Save raco/2ab3c9af21106143190984a07404a9ae to your computer and use it in GitHub Desktop.
Save raco/2ab3c9af21106143190984a07404a9ae to your computer and use it in GitHub Desktop.
Pipe for type only numbers on inputs text
import {
Directive,
ElementRef,
forwardRef,
HostListener,
Renderer2,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Directive({
selector: '[onlyNumber]',
standalone: true,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OnlyNumberDirective),
multi: true,
},
],
})
export class OnlyNumberDirective implements ControlValueAccessor {
private onChange: (val: string) => void;
private onTouched: () => void;
private value: string;
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
@HostListener('input', ['$event.target.value'])
onInputChange(value: string) {
const filteredValue: string = filterValue(value);
this.updateTextInput(filteredValue, this.value !== filteredValue);
}
@HostListener('blur')
onBlur() {
this.onTouched();
}
private updateTextInput(value: string, propagateChange: boolean) {
this.renderer.setProperty(this.elementRef.nativeElement, 'value', value);
if (propagateChange) {
this.onChange(value);
}
this.value = value;
}
// ControlValueAccessor Interface
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.renderer.setProperty(
this.elementRef.nativeElement,
'disabled',
isDisabled
);
}
writeValue(value: any): void {
value = value ? String(value) : '';
this.updateTextInput(value, false);
}
}
function filterValue(value: any): string {
return value.replace(/[^0-9]*/g, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment