Angular 如何在输入字段中使用PercentPipe
我正在尝试为百分比创建输入字段。我使用PercentPipe来显示百分比。然而,当我输入一些数字时,我得到了错误Angular 如何在输入字段中使用PercentPipe,angular,angular7,angular-pipe,Angular,Angular7,Angular Pipe,我正在尝试为百分比创建输入字段。我使用PercentPipe来显示百分比。然而,当我输入一些数字时,我得到了错误 <input required type="number" min="0" max="100" [ngModel]="viewModel.value | percent:'1.2'" id="limitPercentage" (ngModelChange)="viewModel.value=$event" [formControl]="viewModel.co
<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)"
/>
使用组件中的方法执行此操作 首先在构造函数中导入并添加管道,还要创建一个转换方法
import { PercentPipe } from '@angular/common';
class YourComponent {
constructor(private percentPipe: PercentPipe) {}
toPercent(value) {
return this.percentPipe.transform(value, '1.2');
}
}
您需要将提供程序添加到模块中的提供程序列表中。如果没有,您将收到一个验证
providers: [PercentPipe,...]
我发现使用percentpipe对输入没有好处 我将增值税(税率)作为浮动存储在数据库中,但我想在产品编辑表单上显示为百分比。我怀疑如果不是这样的话会让人困惑 所以percentpipe并不适合,因为它将数字转换为文本字符串。现在我想我可以在保存时转换回数字,但我想在输入中使用数字微调器并处理验证 这就是我的结局 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>% </span>
</mat-form-field>
它们非常简单,您可能希望将它们添加到内联中
3) 我使用的是反应式表单,所以在页面加载时,我会使用http响应“patchValue”表单
this.productForm.patchValue({
prodVatRate: this.toPercent(this.product.prodVatRate),
... more data inserted here
});
4) 最后,在我的表单save/submit中,我将数据转换回float
const p = { ...this.product, ...this.productForm.value };
// change the Vat rate back to a floating point number
p.prodVatRate = this.toDecimal(p.prodVatRate);
我希望它能帮到你。你不能用那样的管子。以下是一个很好的线索,说明了为什么会出现这种错误以及一些解决方法:
this.productForm.patchValue({
prodVatRate: this.toPercent(this.product.prodVatRate),
... more data inserted here
});
const p = { ...this.product, ...this.productForm.value };
// change the Vat rate back to a floating point number
p.prodVatRate = this.toDecimal(p.prodVatRate);