简体   繁体   中英

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.

you 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.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM