问题描述
我正在创建一个添加到文本输入的指令,它需要格式化输入的货币。
我有两个 HostListeners;模糊和聚焦。在模糊事件时,我获取该值,对其进行格式化并将其分配给 ngControl。聚焦后,我将其取消格式化并将其重新分配。
我正在注入 ngControl,我可以使用它的 valuechanges 并对其进行格式化,但其他一些代码将值设置为 emitEvent false,因此不会触发。因此它不会格式化它。
我想看看是否有一个可以使用的事件,它会被emitEvent false 触发。
constructor(private currencyPipe: CurrencyPipe,private ngControl: NgControl) {}
@HostListener('blur',['$event']) format(event) {
let value = event.target.value;
if (value ) {
value = this.format(value );
this.ngControl.control.setValue(value,{ emitEvent: false });
}
private format(value: any) {
if (value && value !== '-' && !isNaN(value)) {
return this.currencyPipe.transform(value,this.currencyCode,'',this.digitsInfo,this.locale);
}
return value;
}
HTML
<mat-form-field color="accent" [appearance]="formFieldAppearance" class="table-column-input mr-n1">
<input
autocomplete="off"
appCurrencyFormatter
matInput
formControlName="exchangeRate"
/>
</mat-form-field>
解决方法
HTML
<mat-form-field appearance="outline" class="common-form-field-width"> <mat-label>{{ 'PRICE' | translate:lang }}</mat-label> <input type="number" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" matInput formControlName="actual_price" [value]="actual_price" [placeholder]="'PRICE' | translate:lang" (ngModelChange)="onChangePrice($event)"> </mat-form-field>
Component.ts 文件
onChangePrice(event: any) {
console.log(event);
}