2

I'm tying to understand how to properly build the RxJS based Store approach for handling states in my Angular application. Perhaps I'm missing something very simple.

The example is as follows:

  • I have Reactive Form bind to UI elements, where one of them is <input type="number"/>;
  • I subscribe to myForm.valueChanges and update my store when changes occur;
  • The store does some work under the hood, maybe calls server API, and finally updates its state;
  • In the component, I subscribe to the state updates and do myForm.patchValue(val, { emitEvent: false}).

Here is the example: https://stackblitz.com/edit/angular-ivy-qsn6yu?file=src%2Fapp%2Fapp.component.ts

So far this schema works fine, except for the number inputs. The problem is that I can't input numbers such as 0.01.

I understand what is happening and why:

  • user enters 0.;
  • the form emits change event with value 0 (because the input has type="number");
  • the store does its job and updates state to 0;
  • finally form value is patched to 0 (effectively removing decimal sign or any trailing zeros).

But I would like to understand how such cases are addressed in real-world application (e.g. in bookkeeping where almost all fields are numbers).

Some ideas I considered so far:

  • use input type="text" and pattern based validation, but then on mobiles devices full keyboard is shown (instead of numeric);
  • use constructions such as .pipe(distinctUntilChanged(...)) and fire store updates only when "real" numeric changes are done, but it does not work when user wants to correct 0.01 to 0.02 by deleting last digit;
  • implement custom logic for numeric fields and keep two values (the number and the visual representation of it), but then the benefit of reactive forms fades out;

I'm sure there is well known solution for such simple use case, but I was not able to properly formulate the query to the Google. :)

Thanks!

P.S. Updating store on button click / form submit is not an option as I'm working on auto-save feature for my forms.

Vitaljok
  • 594
  • 1
  • 6
  • 13
  • 1
    Check https://stackoverflow.com/questions/19011861/is-there-a-float-input-type-in-html5 – Loop Mar 19 '21 at 09:01
  • 1
    you can try "update:'onBlur'": https://angular.io/api/forms/FormGroup#set-the-updateon-property-for-all-controls-in-a-form-group – Eliseo Mar 19 '21 at 11:02

0 Answers0