Reactive Username Component in Angular

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

Tomasz Kula
May 15, 2018 · 2 min read

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.

Image for post
Image for post
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

Image for post
Image for post
Reactive Range Component

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store