最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to add decimal in angular reactive form control with value starting with 1 and greater - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 4

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./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)
    });
  }

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论