我創建了一個指令來在文本輸入中格式化貨幣。blur 和 focus 事件有效,但如果 ngModel 中已有值,則不會格式化數字。一旦你給予焦點并離開輸入,它就會正確格式化。在除錯時,您可以在 ngOnInit 期間看到模板更新為格式化的值,但是當您單擊繼續時,該值不再格式化。
金錢輸入.directive.ts
import { CurrencyPipe } from '@angular/common';
import {
Directive,
EventEmitter,
HostListener,
Injector,
Input,
Output,
} from '@angular/core';
import { NgControl, NgModel } from '@angular/forms';
@Directive({
selector: '[moneyInput]',
providers: [NgModel],
host: {
'(input)': 'onInputChange($event)',
},
})
export class MoneyInputDirective {
@Input() ngModel;
@Output() ngModelChange: EventEmitter<any> = new EventEmitter();
value: number;
private control: NgControl;
constructor(private currencyPipe: CurrencyPipe, private injector: Injector) {}
ngOnInit() {
this.control = this.injector.get(NgControl);
if (!this.control || !this.control.valueAccessor) {
return;
}
this.value = Number(this.ngModel);
this.formatCurrency();
}
@HostListener('blur') onBlur() {
this.formatCurrency();
}
@HostListener('focus') onFocus() {
this.control.valueAccessor.writeValue(this.value);
}
onInputChange($event) {
if (!isNaN(Number($event.target.value))) {
this.value = Number($event.target.value);
}
this.ngModelChange.emit(this.value);
}
formatCurrency() {
if (!isNaN(Number(this.ngModel))) {
this.control.valueAccessor.writeValue(
this.currencyPipe.transform(this.ngModel)
);
} else {
this.control.valueAccessor.writeValue('');
}
}
}
app.component.html
<input type="text" [(ngModel)]="model" moneyInput />
鏈接到 StackBlitz 專案 https://stackblitz.com/edit/angular-money-input-directive?file=src/app/app.component.html
uj5u.com熱心網友回復:
將格式移到超時后面:
setTimeout(() => {
this.control.valueAccessor.writeValue(
this.currencyPipe.transform(this.ngModel)
);
})
這樣它就會進入另一個消化周期,這似乎使它起作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409349.html
標籤:
