Wednesday, January 30, 2019

Write a compound number range picker in Angular 6

The reason of this component is that I need a custom input for users to decide their budget, include minimum and maximum, 2 numbers. And lately I found that this input could be reusable in many cases, while itself defined in features as below:



  1. a compound input with 2 number fields: minimum and maximum.
  2. maximum should always be greater than minimum, vice versa.
  3. There is a global maximum, which both minimum and maximum can not exceed it, and correspondingly a global minimum, which hold the lower limit for both minimum and maximum.
  4. Same as a single number input, both minimum and maximum should be controlled by either a slider or directly key in a html number input.
  5. While there are sliders there should also be a variable called "step" which defines the size of increment/decrement between slider ticks.

First of all, let's implement it as an Angular ControlValueAccessor, I really love this sugar because I can communicate the inner value through either ng-model way or the reactive form way.

For feature 1, we create a simple class NumberRange for it. see the implementation below.


This class itself also holds the functionality for feature 2, by doing some checks in setters, like if minimum is greater than maximum, switch them blah blah... you know how it happens.

Feature 3 is also brought about by adding component @Input()s of globalMin and globalMax, also Feature 5 as globalStep. These 3 variables will act as config options set by the components' parent, but not open to users, unnecessary.

As for feature 4, the 2 inputs, slider and number input, can be synced through Angular's built-in change detection, but since we have to emit the change event outwards anyway, we'll wrap them with setters and getters, too.

The complete implementation of the NumberRangeControlComponent:





No comments:

Post a Comment