如何在输入字段中使用 PercentPipe [英] How to use PercentPipe in input field

查看:24
本文介绍了如何在输入字段中使用 PercentPipe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为百分比创建输入字段.我正在使用 PercentPipe 来显示百分比.但是当我输入一些数字时出现错误

I am trying to create input field for percentage. And I am using PercentPipe to display percentage. However I am getting error when I input some number

<input required type="number" min="0" max="100"
   [ngModel]="viewModel.value | percent:'1.2'" id="limitPercentage"
   (ngModelChange)="viewModel.value=$event"
   [formControl]="viewModel.control"
   name="limitPercentage" class="form-control"
   (showErrorMessage)="showErrorMessage($event)"
/>

控制台错误:

 ERROR Error: InvalidPipeArgument: '0% is not a number' for pipe 'PercentPipe'

推荐答案

我发现使用百分比管道对输入没有好处.

I found that using the percentpipe was no good for inputs.

我将增值税(税率)税率存储为我的数据库中的浮点数,但我想在产品编辑表单上将其显示为百分比.我怀疑否则会令人困惑.

I am storing the VAT(Tax rate) rate as a float in my db, but I wanted to show this as a percentage on the product edit form. I suspect it would be confusing otherwise.

因此,percentpipe 不太适合,因为它将数字转换为文本字符串.现在我想我可以在保存时将数字转换回,但我想在输入中使用数字微调器并处理验证.

So the percentpipe isn't a great fit as it transforms numbers into text strings. Now I guess I could have transformed the number back on save, but I wanted to use the number spinner in the input and to handle the validation.

这就是我最终的结果......

So this is what I ended up with...

1) 在表单中我有一个输入

1) in the form I have a input

    <mat-form-field class="col-12 col-sm-6 col-md-2" >
      <mat-label>VAT rate </mat-label>
      <input type="number" matInput formControlName="prodVatRate" 
             min="0" max="100" pattern ="^0?[0-9]?[0-9]$|^(100)$">
          <span matPrefix>%&nbsp;</span>
        </mat-form-field>

2) 在组件中,我有几个简单的函数来处理转换.

2) in the component I have a couple of simple functions to handle the transform.

toPercent(floatingNumber: number): number  {
   return floatingNumber * 100;
}

toDecimal(integerNumber: number): number {
    return integerNumber / 100;
}

它们非常简单,您可能想要内联添加它们.

they are so simple you might want to add them inline.

3) 我使用的是响应式表单,所以在页面加载时我用 http 响应patchValue"表单...

3) I'm using reactive forms so at page load I "patchValue" the form with the http response...

this.productForm.patchValue({
  prodVatRate: this.toPercent(this.product.prodVatRate),
  ... more data inserted here
});

4) 最后在我的表单保存/提交中,我将数据转换回浮点数.

4) and finally in my form save / submit, I transform the data back to a float.

    const p = { ...this.product, ...this.productForm.value };

    // change the Vat rate back to a floating point number
    p.prodVatRate = this.toDecimal(p.prodVatRate);

希望能帮到你.

这篇关于如何在输入字段中使用 PercentPipe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆