Netanel Basal

Learn development with great articles

A Simple, Reusable Solution for Binding URL Query Params to Angular Forms

--

A common behavior in web applications is to sync data in forms based on the values of the URL query params. For example, we may have a page with filters such as search input, and a select box where we can filter by category:

And what we usually want is to add the ability to fill the form when it loads, based on the state of the query params:

http://popo.com/todos?search=angular&category=two

Let’s create a bindQueryParam directive that adds this functionality:

First, we take as input the name of the key we want to bind to our control. Next, we obtain a reference to the control instance via DI. Lastly, we use the URLSearchParams API to parse the query string and update the control value accordingly. Note that you can also use the built-in Angular router to parse the query string. Let’s use our directive:

Tip: we can also take the name automatically from FormControlName.name property. (if it’s identical to the query param key)

We can take it one step further. If our control names are identical to the query params keys, we can use a directive on the form group level:

Now we can use it only once:

🔥 Join Us

Are you an Angular superstar with a passion for OS? Contribute to ngneat projects and lets create the tools of today and tomorrow!

🚀 In Case You Missed It

Here are a few of my open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • error-tailer — Seamless form errors for Angular applications
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests
  • Error Tailor — Seamless form errors for Angular applications

And many more!

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (5)