简体   繁体   English

angular4指令在HTML SPAN标签内不起作用

[英]angular4 directive not working inside HTML SPAN tag

I have written a directive in angular4, which works on input fields. 我已经在angular4中编写了一条指令,该指令适用于输入字段。 When I apply that on SPAN tag, it is not working. 当我将其应用于SPAN标签时,它无法正常工作。 Can we apply the directives on SPAN TAG, or is there any work around. 我们可以在SPAN TAG上应用指令吗,还是可以解决?

<span dirTemp>45789</span>

dirTemp actually corrects the value to 45,789 dirTemp实际上将值校正为45,789

import { Directive, HostListener, ElementRef, OnInit, AfterViewInit, AfterViewChecked, AfterContentChecked } from '@angular/core';
@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[dirTemp ]',
})

export class FormatterDirective implements AfterViewChecked {
  private el: HTMLInputElement;

  constructor(
    private elementRef: ElementRef,
    private cPipe: MyPipe
  ) {
    this.el = this.elementRef.nativeElement;
  }

  // ngOnInit() {
  //  this.el.value = this.cPipe.transform(this.el.value);
  // }

  ngAfterViewChecked(): void {
    this.el.value = this.cPipe.parse(this.el.value);
    this.el.value = this.cPipe.transform(this.el.value);
  }

  @HostListener('focus', ['$event.target.value'])
  onFocus(value) {
    console.log('in formatter directive:', value);
    this.el.value = this.cPipe.parse(value);
  }

  @HostListener('focusout', ['$event.target.value'])
  onFocusout(value) {
    this.el.value = this.cPipe.transform(value);
  }

}

Workaround: span doesn't have value but has innerText or innerHTML . 解决方法: span没有value但具有innerTextinnerHTML So, On ngOnInit you can do: 因此,在ngOnInit您可以执行以下操作:

 ngOnInit() {
    if(this.el.tagName.toUpperCase() !== 'INPUT') {
      //  Apply your tranform here:
      var originalValue =  this.el.innerText;
      this.el.innerText = this.cPipe.transform(originalValue);
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM