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.
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.
Share Improve this question asked Nov 4, 2020 at 13:34 Balaj KhanBalaj Khan 2,5802 gold badges20 silver badges30 bronze badges4 Answers
Reset to default 4you can achieve this using angular DecimalPipe
inside your form template.
<form [formGroup]="myForm">
<input
[value]="myForm.get('global_velocity_weight').value | number" // here you pipe the value
formControlName="global_velocity_weight"
...
>
</form>
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})?$')] })
})
I think your best shot would be to apply a mask to the input field. I know of a library (https://github./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.
- 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)
});
}