我已经编写了自定义指令来格式化数字(例如:BE06377004247122 至BE06 3770 0424 7122)。我不想更改模型值。因此,我为元素分配了格式化的值。与该控件进行任何交互后格式化的值。但最初,它没有改变。值在afterviewinit中格式化,但未反映在控件中。
@Directive({ selector: "[ibanFormatter]" })
export class IBANFormatterDirective implements AfterViewInit {
private el: HTMLInputElement;
private ibanPipe: FormatIBANAccountNumberPipe
constructor(
public model: NgModel,
private elementRef: ElementRef,
)
{
this.el = this.elementRef.nativeElement;
this.ibanPipe = new FormatIBANAccountNumberPipe();
}
ngAfterViewInit() {
this.el.value = this.ibanPipe.transform(this.model.model);
}
@HostListener("focus", ["$event.target.value"])
onFocus(value) {
this.el.value = this.ibanPipe.parse(value); // opossite of transform
}