Angular2 - Input Field To Accept Only Numbers
Looking for a fast solution? Simply bind the keydown
event to a method that rejects non-digit keys in your Angular application.
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
andHome
: 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
.
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!
Was this article helpful?