在我的角应用程序中,我使用的是指令格式化数字。该指令在html中使用,如下所示。
HTML
打字稿
@Directive({
selector: '[numFormatter]',
})
export class FormatterDirective implements OnInit {
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private currencyPipe: NumberPipe
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.el.value = this.currencyPipe.transform(this.el.value);
}
@HostListener('focus', ['$event.target.value'])
onFocus(value) {
this.el.value = this.currencyPipe.parse(value); // opossite of transform
}
@HostListener('focusout', ['$event.target.value'])
onBlur(value) {
this.el.value = this.currencyPipe.transform(value);
}
}
当我们关注该领域时,该指令很有效。我想在组件加载时使用此指令,以便这样做 如果inout字段中有值,则应该格式化。 我不确定我应该使用HostBinding还是应该使用不同的方法。