Reactive Username Component in Angular

Keeping Form Controls in Sync with Angular Reactive Forms - Part 1

We will start by creating the FormGroup and setting up the proper html bindings.

Next, we have to implement the reactiveUsername method.

Our goal is to set the username based on the first and last name values. If the user enters Bruce as the first name and Wayne as the last name, we would like to suggest Bruce-Wayne as the username.

Since our username depends on the latest values emitted from either, firstName or lastName controls, we will use the combineLatest operator.

We pipe the values emitted from combineLatest through a map operator. If both values are present, we simply join them with a dash. Otherwise we set the username to an empty string.

Of course you could implement it differently. Maybe you are fine with deriving the value of the username from just first or last name. In any case, all it would take is a different function passed to the map operator.

And that’s it! We have a working form.

Reactive Username Component

As a final touch, I’d like show how to unit test this component.

One of the best parts of Reactive Forms is the ease of testing it provides. Everything happens synchronously in the component file so we can test it with few simple assertions.

Other than the boilerplate needed to set up the TestBed , we simply set the first and last name values, and assert the expected value of the username control.

Complete example

Github repo

Live demo

In the next part, we will implement reactive range component. Here’s a sneak peek

Reactive Range Component

That’s all for today. If you like the content, please clap 👏👏👏