Angular Material Phone Input
You probably have seen the example on Angular Material website for a custom phone number input, in case you haven’t already, check it out here.
As badass as it looks, it is not production-ready (to be fair the guide says “this is not intended to be a robust component, just a starting point for us to learn.”). We needed a phone input component like this so I decided to spend some time maturing this. It turns out the functionality was pretty close to being production-ready (at least to what we needed).
TL;DR
Check out this bad boy to see the final result
Explanation
Before I dig into the details of what’s missing it would be a good idea to look at the description of the documentation page to get an idea of what’s going on inside this custom directive (I personally couldn’t have understood what was going on without looking at the descriptions, there are a lot of moving parts!). In simple words, this was done with 3 individual input elements under the hood.
So after playing around with the one on the documentation page you soon realize in order to put in a phone number you need to press tab to go to the next section. Besides that, it gets really hectic when you want to remove the entered numbers, you basically need to click each section and remove the characters. Wouldn’t it be awesome if all of this happened automatically while you were typing?
To The Rescue
As you may have guessed from the previous section, we need to implement two different mechanisms:
- Autofocus the next input, once done with the current section
- Autofocus the previous input when backspace is pressed and there isn’t any character left in the current section
Autofocus Next
To automatically focus the next input when done with the previous one we modify the _handleInput function to the following:
Next, we add template reference to all three input variables and pass them into _handleInput:
This will do it for autofocusing the next input while typing
Autofocus Previous
The next part of the puzzle is to have a mechanism in place to allow autofocusing backward when pressing backspace. To do so we use “keyup.backspace” event on the second and the third inputs (obviously the first one doesn’t need one):
And autoFocusPrev is defined as follows:
And just like that backspacing will now keep removing all the way to the first input:
Final Touches
There were a few other things I also added on top of it. First I slightly changed the implementation of onContainerClick, it now focuses on the last filled input on click. I’m also using maxLength on the inputs to not allow more characters than the size of the input.
And that was it, Angular team had already done most of the heavy-lifting it just needed some minor enhancements.
Till the next time I write another one of these: