如何将格式化值显示为用户类型,但将原始值发送到 Angular 4 formControl 进行验证和 formCont



我是Angular2/4的新手。

我有一个 formControlName = "Price" 的输入字段,我需要在用户键入时以正确的货币格式显示输入值。当用户键入"100000"时,我需要将其显示为"Rp100,000",但原始值应按原样发送到 FormControl 值。

我试过这样的:

import { Directive, ElementRef, HostListener } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appPriceInput]'
})
export class PriceInputDirective {
constructor(private el: ElementRef, private control: NgControl) {}
@HostListener('ngModelChange')
onValueChange($event) {
let value = this.el.nativeElement.value;
if (value.toLowerCase().indexOf('rp') !== -1) {
value = this.onRemoveCurrencyPipe(this.el.nativeElement.value);
}
const formattedValue = new CurrencyPipe('en').transform(value, 'IDR', 'symbol-narrow', '1.0-0');
this.control.valueAccessor.writeValue(formattedValue);
}
@HostListener('blur')
onBlur($event) {
const rawValue = this.onRemoveCurrencyPipe(this.el.nativeElement.value);
this.control.viewToModelUpdate(rawValue);
}
onRemoveCurrencyPipe(data) {
return data
.substr(2, data.length)
.split(',')
.join('');
}
}

下面是表单组和验证。价格应该只是一串数字。

createMedicineForm() {
this.medicineForm = this.fb.group({
medicineName: ['', Validators.required],
quantity: [1, [Validators.required, Validators.pattern('^[0-9]*$'), Validators.min(1)]],
unit: ['tablet', Validators.required],
price: [null, [Validators.required, Validators.pattern('^[0-9]*$')]],
medicineId: ''
});
}

但结果仍然是错误的。似乎这里的问题是this.control.valueAccessor.writeValue(formattedValue)this.control.viewToModelUpdate()的错误实现。

有人对正确的实现有任何想法吗?

谢谢。

使用简单的 css 可以添加正确的货币格式,如下所示

.price {
position: relative;
display: block;
}
.price:before {
content: "Rp";
font-size: 18px;
position: absolute;
top: 0px;
left: 75px;
}
.price> input {
padding-left: 25px;
}

Html 将是

<div class="price">
Input here: <input type="text" formControlName="Price"/>
</div>

根据情况更改左填充的值,左填充。

最新更新