Angular 16 Preview: Component Input Bound to Router

Ok, this was one of the features I was most excited about because I often find myself writing a lot of code to do something very simple: get a router param. What am I talking about? Let’s have a look at an example.

Let’s say we have a web app, and the web app has the option for a router param like this https://myapp.com/contactForm?name=john&email=jdoe@fakemail.com, and passing these parameters would allow us auto-fill in the contact form. How might we accomplish this?

The Old Way

Let’s have a peek at how we would do this before Angular 16.

There’s a lot going on here, so let’s start at the very top. This component is set as a route. It has a contactForm which is a FormGroup that holds 3 FormControls:

  • firstName

  • email

  • comments

These are the controls we want to auto-fill using our route params. Since we have the form controls bound to a form in the DOM, we have to inject ActivatedRoute into the constructor of our route and then subscribe to the queryParams. Then in the subscription, we can check for the parameters we want and fill them in. Since this is a subscription, we also have to make sure we clean up after ourselves, so we need to make sure that when the component is destroyed that we unsubscribe from this subscription to avoid potential memory leaks. This is a lot for a little payoff, in my opinion.

The New Way

At the time of writing this, the current version of Angular 16 is 16.0.0-rc.2, and that’s the version I’ll be using. Let’s have a look at the exact same functionality. Before we can get into that, there’s one small thing you need to do before this will work.

This is the small piece of magic that will make this whole thing work: bindToComponentInputs make sure that’s set to true, and the rest will just work. Let’s have a look.

Already this feels a lot better. So what’s going on here? Since we set bindToComponentInputs to true we can simply use the Input decorator to grab a query parameter. When we navigate to https://myapp.com/contactForm?name=john&email=jdoe@fakemail.com our inputs will be bound to the query params! That’s it. The only other thing you have to do is use these Input variables in your OnInit since they won’t be available in the constructor. 

This helps us out in 2 ways

  1. It’s easy to read

  2. It cleans up the code so we don’t have subscriptions that we have to manage manually

A small caveat

There is a small caveat on the first point, though, and this was brought up in the PR to get this feature.

The Input decorator is already used for passing variables into your component, so this can muddy the water between component input and query parameters. The suggested fix for this is to create a new name for the decorator that binds the query parameters. Hopefully, this fix is put in place before the release of Angular 16, but I guess we’ll see. 

Previous
Previous

Angular 16: Required Inputs

Next
Next

SocialGPT’s Progress 1 Week Later