Enter only numbers in input using this directive in the Angular application

Roman Akhromieiev
2 min readJun 8, 2024

--

A case when we must only enter numbers in input happens very often.

Let’s create a directive that will trim the value and allow you to enter only numbers without any special symbols. The usage will look like this:

<!--ngModel-->
<input [(ngModel)]="value" numbersOnly />

<!--Reactive forms-->
<form [formGroup]="formGroup">
<input formControlName="value" numbersOnly />
</form>

In our directive, we will use ngControl to implement this functionality. Using ngControl we can have access to ngModel directives and forms directives. I recommend you to familiarize yourself by reading the article about why we need to stop re-implement ControlValueAccessor. We need to create a basic directive, inject NgControl, and listen to changes.

The code of our directive:

import { Directive, AfterViewInit, inject, DestroyRef } from '@angular/core';
import { NgControl } from '@angular/forms';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Directive({
selector: 'input[numbersOnly]',
standalone: true,
})
export class NumbersOnlyDirective implements AfterViewInit {
private ngControl = inject(NgControl);
private destroyRef = inject(DestroyRef);

ngAfterViewInit(): void {
this.ngControl.valueChanges
?.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((value: string) => {
const initialValue =
typeof value === 'string' ? value.replace(/[^0-9]/g, '') : '';

if (value !== initialValue) {
this.ngControl.control?.setValue(initialValue, { emitEvent: false });
}
});
}
}

It listens to the value and replaces any letters, or symbols using regular expression. If the string has non-numeric symbols regex expression replaces them with an empty string and keeps only numbers. The pros of this directive are it automatically works with ngModel and FormControls, so we can cover cases with template-driven and reactive forms.

Feel free to grab Stackblitz example of this Angular directive.

Follow me on Medium or Twitter to read more about Angular, Web, Pet-projects!

--

--