首页 > 解决方案 > 如何在组件加载时使用角度 Hostlistener

问题描述

在我的角度应用程序中,我使用了一个格式化数字的指令。该指令在 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 字段中有一个值,它应该被格式化。不确定 II 应该使用 HostBinding 还是我们应该使用不同的方法。

标签: angularonload

解决方案


推荐阅读