0

I have some troubles. The customers requests us with condition in input as

  1. step 1: User want to display number with decimal 2 places
  2. step 2: User are focusing in input => display full number
  3. step 3: Out focusing in input => display such as step 1
  4. step 4: User click on Save button. We still store data with full number

For ex: User input 23.33324 => out focus, display on input is 23.3 => in focus => 23.33324 => save data into db => 23.33324

How to do that in angualr 10 (using formgroup)? Thanks.

Englbach
  • 75
  • 8

2 Answers2

1

The reusable and best way would be to create your own custom FormControl, ie. a component which implements ControlValueAccessor. Docs: https://angular.io/api/forms/ControlValueAccessor

There are plenty of tutorials out there too.

funkizer
  • 4,626
  • 1
  • 18
  • 20
1

Update Another approach in this SO

a FormControl exist even if there're no input, so you can use a [ngModel] (ngModelChange)

declare an empty array of booleans (*)

focus:boolean[]=[]

And use some like:

<form [formGroup]="myform">
  <input style="text-align:right"
  [ngModel]="focus[0]?myform.get('control').value:(+myform.get('control').value).toFixed(2)"
  (ngModelChange)="myform.get('control').setValue($event)"
  [ngModelOptions]="{standalone:true}"
  (focus)="focus[0]=true" (blur)="focus[0]=false">
</form>

Update you can also "format the number" using the angular formatNumber function -the function that use pipe number-. Just create a function format

  import {formatNumber} from '@angular/common'
  format(number:number)
  {
    return formatNumber(number,'en-US','0.2-2')
  }

And replace the [ngModel] in the input by

[ngModel]="focus[1]?myform.get('control2').value:format(+myform.get('control2').value)"

See the stackblitz

(*)I imagine you has severals "inputs", so for one of then use focus[0], for another one focus[1]...

Eliseo
  • 50,109
  • 4
  • 29
  • 67