How To Format A Value with Angular NGX-Formly
A handy way to format postal codes, phone numbers, bank accounts, and so much more
Table of contents
Working with forms is a nightmare in the current state of Angular (yes, thatβs my opinion)! You have to do so much manual work, which is not very productive while building enterprise-level applications.
Thatβs why I love to use NGX-Formly ! They make writing small, big, and even complex forms easier. (You can read earlier posts below π) But lately, I have wanted to change the format of input values after the user has filled them in. Because there is a certain way, the backend API expects them.
If you donβt know how to use NGX-formly, I highly recommend following my earlier posts (they are even included in the documentation from NGX-formly itself π)
- Build Fast, JSON-Powered Forms on Angular With Ngx Formly
- How to Build Fast, Advanced JSON-Powered Forms on Angular With ngx-formly
NGX-Formly Formatters
For example, we want to create a postal code field and a field for initials. In these fields, we want to apply specific formatting on the value. In this case, it will be visual formatting, nothing very complex.
The logic behind the formatInitials()
method looks like this.
Formatters
So every field that needs a formatter needs a property parser.
{
//...
parsers: [(value: string) => value?.toUpperCase()],
//...
}
The parser needs to be an array of functions. Every function has a parameter that holds the value. Since the parsers need an Array, you can apply multiple formatters on every field.
The function needs to return a new value. So it can be updated in the input field.
Ensure that the field config also has the property expressionProperties
in which the model is updated; otherwise, it will not work.
expressionProperties: {
'model.postal': 'model.postal',
},
Example
Iβve created an example project for this tutorial via StackBlitz, which you can use to experiment with the parsers.
If you want to check the project on Github, please find the repository here.
Conclusion
Hopefully, this tutorial helps you to format your values easier with NGX-Formly. And if you didn't use NGX-Formly, I hope this will let you build forms even faster!
Good luck and have fun π
Happy Coding π
Thanks!
I hope you learned something new or are inspired to create something new after reading this story! π€ If so, consider subscribing via email (scroll to the top of this page) or follow me here on Hashnode.
Did you know that you can create a Developer blog like this one, yourself? It's entirely for free. ππ°ππ₯³π₯
If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM's are always open π