Explain Codes LogoExplain Codes Logo

Angular2 - Input Field To Accept Only Numbers

javascript
directive
input-field
angular2
Anton ShumikhinbyAnton Shumikhin·Sep 7, 2024
TLDR

Looking for a fast solution? Simply bind the keydown event to a method that rejects non-digit keys in your Angular application.

<input type="text" (keydown)="rejectNonNumeric($event)">
rejectNonNumeric(event): void { // If it's not a number, it's not allowed in! if (event.key && !event.key.match(/^\d+$/)) { // Event.preventDefault: A developer's "talk to the hand" ⛔ event.preventDefault(); } }

This approach checks the key pressed; if it's not a digit (0-9), it blocks the input. Simple, but effective.

Keep functional keys functional

When implementing a directive for number-limited input, remember to consider functional keys for a better user experience:

  • Backspace, Tab, End and Home: Users should still be able to interact naturally with the input field
  • Clipboard operations: We all like a good shortcut, so leave the ctrl + C/V/X commands out of your directive.
  • Browser compatibility: Browsers aren't all created equal - or consistent. Keep this in mind and do your checks.

Directive that Saves Lives (and Numbers)

Here's how you can create a directive that will stand guard over your input elements, ensuring they only accept numbers.

import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appOnlyNumbers]' }) export class OnlyNumbersDirective { constructor(private el: ElementRef) {} @HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) { let allowedKeys = [ 'Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Delete' ]; // JavaScript Jedi trick: the chosen one shall pass, others shall not! if (allowedKeys.includes(event.key) || this.isNumeric(event.key)) { // Carry on, nothing to see here... return; } else { // I've got 99 keys, but a letter ain't one! event.preventDefault(); } } private isNumeric(value: string): boolean { // 007 is allowed because we like James Bond, but others... no so much. return /^\d+$/g.test(value); } }

Input Handling Redux

Implementing this kind of directive can come with more considerations:

World-friendly coding

Key codes vary depending on keyboard layouts and languages. Welcome diversity, accommodate different configurations.

Every event matters

Adding change and paste events can handle more diverse input scenarios, such as mouse pasting. Because mice matter too!

DOM manipulation - use with caution

Directly manipulate the host element using el.nativeElement. Use responsibly — Angular's unidirectional data flow principles are watching!