• 2 min

How To Format a Value With Angular NGX-Formly

How To Format a Value With Angular NGX-Formly
Table of Content

Creating forms in Angular with NGX-Formly is super easy. But sometimes you want a little more, like formatting postal codes, phone numbers, or bank accounts. In this post, I will show you how you can do it.

I love to use NGX-Formly! They make writing small, big, and even complex forms easier. 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 reading the below posts.
  1. Build Fast, JSON-Powered Forms on Angular With Ngx Formly
  2. 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.

So every field that needs a formatter needs a property parser.

ts
{  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.

ts
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.


Thanks!

After reading this post, I hope you learned something new or are inspired to create something new! 🤗

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 😁

RayRay

I’m Ray, a Frontend Developer since 2009 living in the Netherlands. I write about Frontend Development, JavaScript, TypeScript, Angular, CSS, VueJS and a lot more related topics.

Want to reach me for comments or questions on my blog? Send a DM on Twitter @DevByRayRay