Reactive Range Component in Angular

Keeping Form Controls in Sync with Angular Reactive Forms — Part 2

In part 1 we created reactive username component which sets the username based on the first and last name values.

In this article we will create a reactive range component.

Reactive Range Component

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

The reactive logic for the component consists of two things:

rangeEnd should match rangeStart if rangeStart is increased above rangeEnd's value

rangeStart should match rangeEnd if rangeEnd is decreased below rangeStart's value

We can express this intended behavior with the following unit tests.

At this point tests fail and we must implement the reactiveRange method to make them pass.

As we asserted, end should match the start if start is increased above end’s value. We can achieve this by piping the start's value changes stream through a filter function. The filter function simply compares the controls’ values.

The end control stream will follow the exact same steps, but with a different predicate function passed into the filter operator.

And that’s it! We have a working reactive range component.

Reactive Range Component

If you are interested in how to create a custom validator for the range component, check out Angular Cross Field Validation

Complete example

Github repo

Live demo

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