【问题标题】:How to use PercentPipe in input field如何在输入字段中使用 PercentPipe
【发布时间】:2019-09-18 13:18:14
【问题描述】:

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

<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'

【问题讨论】:

标签: angular angular7 angular-pipe


【解决方案1】:

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

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

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

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

1) 以我有输入的形式

    <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) 在组件中,我有几个简单的函数来处理转换。

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

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

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

3) 我使用的是响应式表单,因此在页面加载时,我使用 http 响应“patchValue”表单...

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

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

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

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

希望对你有帮助。

【讨论】:

  • 如果不是在加载阶段到补丁值,你可以添加(focusout)方法。这意味着将步骤3移到(focusout)方法中。
【解决方案2】:

使用组件中的方法来实现。

首先在构造函数中导入并添加管道,同时创建一个transform方法。

import { PercentPipe } from '@angular/common';

class YourComponent {

  constructor(private percentPipe: PercentPipe) {}

  toPercent(value) {
    return this.percentPipe.transform(value, '1.2');
  }
}

你需要在你的模块的提供者列表中添加提供者,如果没有,你会收到一个例外

providers: [PercentPipe,...]

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 2011-04-30
    • 2012-12-06
    • 1970-01-01
    • 2017-07-06
    • 2012-06-07
    • 1970-01-01
    • 2020-06-14
    • 2015-03-31
    相关资源
    最近更新 更多