【发布时间】:2019-11-19 17:38:42
【问题描述】:
我创建了一个货币指令,我将在每个需要货币格式的输入元素中使用它。
所以我有 2 个 Host Listeners,一个是 OnFocus,第二个是 Blur
而且效果很好。但是我通过绑定设置输入值的时候需要格式化输入的值
因此,当我打开一个模式时,我会得到未格式化的值... NgOnInit 不起作用,因为它提得太早了
这是我的指令代码。
import { Directive, HostListener, Input, OnInit, ElementRef, AfterViewInit, OnChanges, Renderer2, ViewChild } from '@angular/core';
import { CurrencyPipe, getCurrencySymbol } from '@angular/common';
import { NgControl, ControlValueAccessor } from '@angular/forms';
import { CustomCurrencyPipe } from '../pipes/custom-currency.pipe';
import { ModalDirective } from 'ngx-bootstrap/modal';
@Directive({
selector: '[appCurencyFormat]',
providers: [CustomCurrencyPipe]
})
export class CurrencyFormatDirective implements OnInit{
//@Input('appNumberFormat') params: any;
@Input() decimalNumber: number = 2;
@Input() symbol: string = "symbol";
//@Input() OnlyNumber: boolean;
local: string;
decimal: string;
currency: string;
element: any;
@ViewChild(ModalDirective) childModal: ModalDirective;
constructor(private elementRef: ElementRef, private ngControl: NgControl, private currencyPipe: CustomCurrencyPipe, private _renderer: Renderer2) {
this.element = this.elementRef.nativeElement;
}
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent>event;
//190 in array for .
if ([46, 8, 9, 27, 13, 110].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+C
(e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+V
(e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+X
(e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
@HostListener('focus', ['$event.target.value'])
onFocus(value: any) {
this.ctrl.setValue(this.currencyPipe.convertToNumber(value));
}
@HostListener('blur', ['$event.target.value'])
onBlur(value: any) {
this.ctrl.setValue(this.currencyPipe.transform(value, this.decimalNumber, this.symbol));
}
get ctrl() {
return this.ngControl.control;
}
}
我的解决方案是在 ngOnInit 中设置间隔...
ngOnInit() {
let m = window.setInterval(() => {
console.log("Upao sam");
console.log(this.ctrl.value);
if (this.ctrl.value) {
console.log(this.ctrl.value);
if (seted) {
window.clearInterval(m);
} else {
seted = true;
this.ctrl.setValue(this.currencyPipe.transform(this.ctrl.value, this.decimalNumber, this.symbol));
}
}
}, 500);
}
有谁知道我可以使用哪个 HostListener,尽量避免使用window.setInterval()。或者如果有人知道我该如何解决这个问题?
更新
ngOnChanges() 不是每次都被提出,所以选择的重复问题无法解决我的问题。
【问题讨论】:
-
@jonrsharpe 只是可能... ngOnChanges 不会每次都提高
-
使用已经可用的currency-pipe有什么挑战
-
您不能在输入中使用它。第一次您将输入例如 500,管道将返回 $500,下次如果您想使用管道,则需要删除 $,因为管道期望数字而不是字符串
-
你能创建一个关于这个问题的 stackblitz/codesandbox 演示吗?
标签: angular format currency angular-directive