'how to add decimal in angular reactive form control with value starting with 1 and greater

I want to add a decimal and then 0 after 1 like 1.0

<input type="number" formControlName="global_velocity_weight" />

this.form = this.fb.group({
   global_velocity_weight: new FormControl(1.0, { validators: [Validators.required] })
})

But it is not working and in the input, only 1 is shown.



Solution 1:[1]

You should make some regular expression to accept numeric values:

 <input type="number" formControlName="global_velocity_weight" />
    
    this.form = this.fb.group({
       global_velocity_weight: new FormControl(1.0, { validators: 
    [Validators.required,Validators.pattern('^[0-9]+(.[0-9]{0,1})?$')] })
    })

Solution 2:[2]

I think your best shot would be to apply a mask to the input field. I know of a library (https://github.com/JsDaddy/ngx-mask) that allows you to do so and I believe it's supported from Angular 5 up.

A mask is a specification of what the input should look like, like yyyy/mm/dd you see often for date inputs. You can also use this to specify how a number input field should look like and indicate the appearance of decimals.

Solution 3:[3]

  • Binding (blur) event handler did the trick.
  • You can even bind (change), (keyup), (keypress) event handler to run event based on requirement.
  <mat-form-field>
     <mat-label>LABEL</mat-label>
     <input matInput type="number" min="1" formControlName="CONTROL_NAME" required blur="onBlurTruncateDecimalPart('CONTROL_NAME')">
  </mat-form-field>
 onBlurTruncateDecimalPart(formControlName: string) {
    this.productFormGroup.patchValue({
      [formControlName]: Math.trunc(this.FORM_GROUP.get(formControlName).value)
    });
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rebai Ahmed
Solution 2 Eduard Keilholz
Solution 3 khizer